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

问题描述

我有一个NSMutableArray对象,我想添加自定义方法。我试图子类化NSMutableArray,但然后我得到一个错误说方法只定义为抽象类,当试图获得对象的计数方法的数量。为什么不继承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类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 17:12