stu*_*ped 6 singleton objective-c alloc
BNRItemStore是一个单身人士,我很困惑为什么super allocWithZone:必须被称为而不是简单的旧super alloc.然后覆盖alloc而不是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
Run Code Online (Sandbox Code Playgroud)
Jos*_*ell 10
[super alloc]将打电话给allocWithZone:你,你已经覆盖了做其他事情.为了实际获得超类的实现allocWithZone:(这是你想要的)而不是被覆盖的版本,你必须allocWithZone:明确发送.
的super关键字表示相同的对象self; 它只是告诉方法调度机制开始在超类而不是当前类中查找相应的方法.
因此,[super alloc]将进入超类,并在那里获得实现,看起来像:
+ (id) alloc
{
return [self allocWithZone:NULL];
}
Run Code Online (Sandbox Code Playgroud)
在这里,self仍然代表您的自定义类,因此,您的重写allocWithZone:被运行,这将把您的程序发送到无限循环.
| 归档时间: |
|
| 查看次数: |
4300 次 |
| 最近记录: |