Here’s my try:
H file:
@interface Strings : NSArray
@end
M file:
@implementation Strings
- (id) init
{
[self initWithObjects:
@"One.",
nil];
return self;
}
@end
When I run I get this:
‘NSInvalidArgumentException’, reason: ‘* -[NSArray initWithObjects:count:]: method only defined for abstract class. Define -[Strings initWithObjects:count:]!’
This is what I did instead:
H file:
@interface Strings : NSObject
+ (NSArray*) getStrings;
@end
M file:
@implementation Strings
+ (NSArray*) getStrings
{
NSArray* strings = [[NSArray alloc] initWithObjects:
@"One.",
nil];
return strings;
}
@end
NSArrayis a class cluster (link to Apple’s documentation). This means that when you try to create anNSArray, the system creates some private subclass ofNSArray. TheNSArrayclass just defines an interface; subclasses ofNSArrayprovide implementations of the interface.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 overrideinitWithObjects:count:in your subclass. Your override needs to put the objects into whatever storage you allocate as part of your class implementation.The
NSArrayimplementation of the variadicinitWithObjects:method is just a wrapper aroundinitWithObjects:count:, so you don’t have to implementinitWithObjects:.