单例是全局的类实例,存放在全局内存里,不能以任何方式复制,也不会被释放。实例化的对象始终指向同一块内存。具体实现方式有两种,线程锁和GCD。代码如下,如有错误欢迎大家批评指正:
线程锁代码:
static id _instance;
+ (User *)shareInstance {
@synchronized(self) {
if (_instance == nil) {
_instance = [[User alloc] init];
}
}
return _instance;
}
+ (id)allocWithZone:(struct _NSZone *)zone {
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
- (id)copyWithZone:(NSZone *)zone {
return _instance;
}
GCD代码:
+(User *)shareInstance {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//onceToken是GCD用来记录是否执行过 ,如果已经执行过就不再执行(保证执行一次)
_instance = [[User alloc] init];
});
return _instance;
}
+ (id)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//onceToken是GCD用来记录是否执行过 ,如果已经执行过就不再执行(保证执行一次)
_instance = [super allocWithZone:zone];
});
return _instance;
}
- (id)copyWithZone:(NSZone *)zone {
return _instance;
}