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