问题描述
BNRItemStore
是一个单例,我对为什么必须调用super allocWithZone:
而不是普通的super alloc
感到困惑.然后覆盖alloc
而不是allocWithZone
.
BNRItemStore
is a singleton, and I was confused on why super allocWithZone:
must be called instead of plain old super alloc
. And then override alloc
instead of 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
推荐答案
[super alloc]
将调用allocWithZone:
,您已对其进行了其他操作.为了真正获得allocWithZone:
的超类的实现(这是您想要的),而不是重写的版本,必须显式发送allocWithZone:
.
[super alloc]
will call through to allocWithZone:
, which you've overridden to do something else. In order to actually get the superclass's implementation of allocWithZone:
(which is what you want there) rather than the overridden version, you must send allocWithZone:
explicitly.
super
关键字表示与self
相同的对象;它只是告诉方法分派机制开始在超类而不是当前类中寻找相应的方法.
The super
keyword represents the same object as self
; it just tells the method dispatch mechanism to start looking for the corresponding method in the superclass rather than the current class.
因此,[super alloc]
将进入超类,并在那里获得实现,如下所示:
Thus, [super alloc]
would go up to the superclass, and get the implementation there, which looks something like:
+ (id) alloc
{
return [self allocWithZone:NULL];
}
在这里,self
仍然代表您的自定义类,因此,您覆盖的allocWithZone:
将运行,这将使您的程序陷入无限循环.
Here, self
still represents your custom class, and thus, your overridden allocWithZone:
is run, which will send your program into an infinite loop.
这篇关于用allocWithZone创建一个单例:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!