我再次讀一本書,有這樣實現類:不清楚爲什麼初始化方法被調用了一些類
@implementation BNRItemStore
// Init method
- (id)init
{
self = [super init];
if(self)
{
allItems = [[NSMutableArray alloc] init];
}
return self;
}
#pragma mark singleton stuff
// Implementing singleton functionality
+(BNRItemStore*) sharedStore
{
static BNRItemStore *sharedStore = nil;
// Check if instance of this class has already been created via sharedStore
if(!sharedStore)
{
// No, create one
sharedStore = [[super allocWithZone:nil] init];
}
return sharedStore;
}
// This method gets called by alloc
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedStore];
}
#pragma mark Methods
// return pointer to allItems
-(NSArray*) allItems
{
return allItems;
}
// Create a random item and add it to the array. Also return it.
-(BNRItem*) createItem
{
BNRItem *p = [BNRItem randomItem];
[allItems addObject:p];
return p;
}
@end
我覺得奇怪的事情是,無處類外,例如,一些其他類,是調用BNRItemStore
的init
方法。不過,還是通過某些手段它被調用,甚至當有人輸入的BNRItemStore
類外這樣的代碼:
[[BNRItemStore sharedStore] createItem]; // This still calls the init method of BNRItemStore. How?
可有人請解釋一下爲什麼?
嗨亞歷山大,這不是我的問題,我知道程序進入if子句,因爲sharedStore是零。問題是,顯然通過調用'[super allocWithZone:nil]''''調用'BNRItemStore'類的'init'上的'init',儘管使用了'super allocWithZone' ......你明白了嗎? – user2054339
啊,對。檢查答案[這裏](http://stackoverflow.com/a/11962942)。 – Alexander