问题描述
如果你使用NSArray的方便方法初始化一个NSMutableArray,你会得到一个NSArray或者NSMutableArray?
任何后果吗?
(我知道NSMutableArray有arrayWithCapacity:,我只是好奇)
初始化它:
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
orNSMutableArray
).这篇关于初始化NSMutableArray:[NSMutableArray array];的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!