Initialize NSMutableArray: [NSMutableArray array];

2020-06-17 05:35发布

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)

2条回答
时光不老,我们不散
2楼-- · 2020-06-17 06:03

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).

查看更多
男人必须洒脱
3楼-- · 2020-06-17 06:04

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]));

查看更多
登录 后发表回答