如何扩展NSArray? [英] How do I extend an NSArray?
问题描述
这是我的尝试:
H档案:
@interface Strings : NSArray
@end
M file:
@implementation Strings
- (id) init
{
[self initWithObjects:
@"One.",
nil];
return self;
}
@end
当我跑步时我得到这个:
When I run I get this:
'NSInvalidArgumentException',原因:' * - [NSArray initWithObjects:count:]:仅为抽象类定义的方法。定义 - [Strings initWithObjects:count:]!'
'NSInvalidArgumentException', reason: '* -[NSArray initWithObjects:count:]: method only defined for abstract class. Define -[Strings initWithObjects:count:]!'
这就是我所做的:
H file :
@interface Strings : NSObject
+ (NSArray*) getStrings;
@end
M档案:
@implementation Strings
+ (NSArray*) getStrings
{
NSArray* strings = [[NSArray alloc] initWithObjects:
@"One.",
nil];
return strings;
}
@end
推荐答案
NSArray
是 类集群(链接到Apple的文档)。这意味着当您尝试创建 NSArray
时,系统会创建一些 NSArray
的私有子类。 NSArray
类只定义了一个接口; NSArray
的子类提供接口的实现。
NSArray
is a class cluster (link to Apple's documentation). This means that when you try to create an NSArray
, the system creates some private subclass of NSArray
. The NSArray
class just defines an interface; subclasses of NSArray
provide implementations of the interface.
您可以编写自己的子类NSArray
,但您必须为数组中的对象提供自己的存储空间。您必须自己初始化该存储。错误消息通过声明您需要在子类中覆盖 initWithObjects:count:
来告诉您这一点。您的覆盖需要将对象放入您作为类实现的一部分分配的任何存储中。
You can write your own subclass of NSArray
, but you have to provide your own storage for the objects in the array. You have to initialize that storage yourself. The error message is telling you this, by saying that you need to override initWithObjects:count:
in your subclass. Your override needs to put the objects into whatever storage you allocate as part of your class implementation.
NSArray
实现variadic initWithObjects:
方法只是 initWithObjects:count:
的包装器,所以你不必实现 initWithObjects:
。
The NSArray
implementation of the variadic initWithObjects:
method is just a wrapper around initWithObjects:count:
, so you don't have to implement initWithObjects:
.
这篇关于如何扩展NSArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!