Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize NSMutableArray: [NSMutableArray array];

If you initialize an NSMutableArray with NSArray's convenience method as above, do you get an NSArray or an NSMutableArray?

Any consequences?

(I know that NSMutableArray has "arrayWithCapacity:, I'm just curious)

like image 694
Corey Floyd Avatar asked May 09 '09 22:05

Corey Floyd


2 Answers

If you initialize it using:

NSMutableArray *array = [NSMutableArray array];

you get a NSMutableArray. One great feature of Objective-C is that class methods are inherited by subclasses.

So, in a class method you can do something like this:

+(id)array {
    return [[[self alloc] init] autorelease];
}

and self will be referencing to the class object where the code is executing (NSArray or NSMutableArray).

like image 166
pgb Avatar answered Sep 22 '22 16:09

pgb


Update: While my advice to "test it yourself" is generally a good idea, it was a little trigger-happy in this case. Thanks to Jim in the comments for pointing at that my suggestion below doesn't work well for these classes, because the various forms of NSArray are all implemented by a CoreFoundation toll-free bridging class.

----- Original Answer For Context Below -----

The easiest way to answer a question like this is to test it yourself. Try allocating the array in the way you were curious about, then NSLog from your code:

NSLog(@"We got a %@", NSStringFromClass([theArray class]));

like image 43
danielpunkass Avatar answered Sep 21 '22 16:09

danielpunkass