GCD实现单例模式
当[[self alloc] init]时,会默认调用+ (instancetype)allocWithZone:(struct _NSZone *)zone;这个方法而这个
方法,就是在给对象分配内存空间,zone想当与一个内存池,allocWithZone,dealloc 都是在这个内粗池中操作。
1. 声明一个静态的对象
static id _instance;
2. 重写copy方法
- (id)copyWithZone:(NSZone *)zone{
return _instance;
}
3. 重写alloc方法
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
4. 构造方法
+ (instancetype)sharedSingleton{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
网友评论