Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extend an NSArray?

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
like image 711
Roger C S Wernersson Avatar asked Jan 22 '12 20:01

Roger C S Wernersson


1 Answers

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.

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.

The NSArray implementation of the variadic initWithObjects: method is just a wrapper around initWithObjects:count:, so you don't have to implement initWithObjects:.

like image 69
rob mayoff Avatar answered Nov 05 '22 09:11

rob mayoff