BNRItemStore
是一個單例,我很困惑爲什麼super allocWithZone:
必須被調用而不是普通的舊的super alloc
。然後覆蓋alloc
而不是allocWithZone
。使用allocWithZone創建一個單例:
#import "BNRItemStore.h"
@implementation BNRItemStore
+(BNRItemStore *)sharedStore {
static BNRItemStore *sharedStore = nil;
if (!sharedStore)
sharedStore = [[super allocWithZone: nil] init];
return sharedStore;
}
+(id)allocWithZone:(NSZone *)zone {
return [self sharedStore];
}
@end
難倒了,這是在ObjC入門課程的一個微妙的一面,所以如果你有關於我的答案的問題,我很樂意澄清。 – 2012-08-15 01:29:06
謝謝!我有一個問題。如果我刪除了重寫allocWithZone的方法:是否可以調用super alloc而不是super allocWithZone:在sharedStore中? – stumped 2012-08-15 01:31:35
是的。覆蓋'allocWithZone:'的原因是限制這個類的任何用戶創建另一個實例。他們會直接調用alloc(或可能是'allocWithZone:';而不是分配一個新的實例,而是返回現有的實例,這是使這個類成爲單例的關鍵部分 – 2012-08-15 01:35:53