有三种方法可以保证当前的程序中只有一个对象实例。
1.GCD
+(instancetype)sharedInstance2
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
single = [[self alloc]init];
});
return single;
}
2.重写allocWithZone:方法
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
static id instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone:zone];
});
return instance;
}
3.普遍的延迟加载写法
+(instancetype)sharedInstance
{
if (single == nil) {
single = [[self alloc] init];
}
return single;
}