我应该继承 NSMutableArray 类吗 [英] Should I subclass the NSMutableArray class

查看:20
本文介绍了我应该继承 NSMutableArray 类吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSMutableArray 对象,我想向其中添加自定义方法.我尝试对 NSMutableArray 进行子类化,但是当我尝试使用 count 方法获取对象数时,我收到一条错误消息,提示仅为抽象类定义的方法".为什么count方法没有被继承?

I have an NSMutableArray object that I want to add custom methods to. I tried subclassing NSMutableArray but then I get an error saying "method only defined for abstract class" when trying to get the number of objects with the count method. Why is the count method not inherited?

我在别处读到,如果我想使用它们,我必须将一些 NSMutableArray 方法导入到我的自定义类中.我只想向 NSMutableArray 类添加一个自定义方法.那么我应该继承 NSMutableArray,还是应该做其他事情?

I read somewhere else that I will have to import some NSMutableArray methods into my custom class if I want to use them. I just want to add a custom method to the NSMutableArray class. So should I subclass NSMutableArray, or should I do something else?

推荐答案

NSMutableArray 不是一个具体的类,它只是一个类簇的抽象超类.NSMutableArray 的文档确实有关于如何子类化的信息,但也强烈建议你不要!仅当您对实际存储有特殊需求时才创建子类.

NSMutableArray is not a concrete class, it is just the abstract superclass of a class cluster. The documentation for NSMutableArray does have information about how to subclass, but also strongly advises you not to! Only subclass if you have a special need for actual storage.

类簇意味着将在运行时选择实际的类.创建为空的数组可能与使用 1000 个项目创建的数组使用不同的类.运行时可以明智地选择要使用的实现.在实践中NSMutableArray 将是一个桥接的CFArray.您无需担心什么,但是如果您在调试器中检查数组的类型,您可能会看到它,您将永远不会看到 NSArray,但经常会看到 NSCFArray.

A class cluster means that the actual class will be chosen at run-time. An array created empty, may not use the same class as an array created with 1000 items. The run-time can do smart choices of what implementation to use for you. In practice NSMutableArray will be a bridged CFArray. Nothing you need to worry about, but you might see it if you inspect the type of your arrays in the debugger, you will never see NSArray, but quite often NSCFArray.

如前所述,子类化与扩展类不同.Objective-C 有类别的概念.类别类似于其他编程语言所称的混入.

As mentioned before, subclassing is not the same as extending a class. Objective-C has the concept of categories. A category is similar to what other programming languages call mix-ins.

例如,如果您希望 NSMutableArray 上的便捷方法对属性上的所有成员进行排序,则在 .h 文件中定义类别接口,如下所示:

If you for example want a convenience method on NSMutableArray to sort all members on a property, then define the category interface in a .h file as such:

@interface NSMutableArray (CWFirstnameSort)
-(void)sortObjectsByProperty:(NSString*)propertyName;
@end

实现将是:

@implementation NSMutableArray (CWFirstnameSort)
-(void)sortObjectsByProperty:(NSString*)propertyName;
{
    NSSortDescriptor* sortDesc = [NSSortDescriptor sortDescriptorWithKey:propertName ascending:YES];
    [self sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
}
@end

然后简单地使用它:

[people sortObjectsByProperty:@"firstName"];

这篇关于我应该继承 NSMutableArray 类吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆