#import "Singleton.h"
@implementation Singleton
static id manager = nil;
+ (Singleton *)manager {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[Singleton alloc] init];
});
return manager;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [super allocWithZone:zone];
});
return manager;
}
- (id)copy {
return [Singleton manager];
}
下面是本人所犯的错误
#import "Singleton.h"
@implementation Singleton
static id manager = nil;
+ (Singleton *)manager {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[Singleton alloc] init];
});
return manager;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
return [Singleton manager]; // 创建对象init的时候会调用该方法,所以这种写法的后果就是进入死循环。无限执行manager方法和本方法。
}
- (id)copy {
return [Singleton manager];
}