且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

初始化NSMutableArray:[NSMutableArray array];

更新时间:2022-10-14 19:55:06

初始化它:

  NSMutableArray * array = [NSMutableArray array]; 
pre>

你得到一个NSMutableArray。Objective-C的一个很大的特点是类方法是由子类继承的。



所以,在类方法中,你可以这样做:

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

self 将引用代码正在执行的类对象( NSArray NSMutableArray )。


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)

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