一个单例类,在整个程序中只有一个实例,并且提供一个类方法供全局调用,在编译时初始化这个类,然后一直保存在内存中,到程序(APP)退出时由系统自动释放这部分内存。
优点:因为一直存在,所以加快了执行效率
缺点:不能被继承,不能有子类;不易被重写或扩展(可以使用分类);占用了内存资源不被释放。。
IOS中为了保持单利的唯一性。我们需要重写
copyWithZone、
mutableCopyWithZone、
allocWithZone(覆盖alloc,new,均会调用allocWithZone)
可普通实现和GCD实现
普通实现
+ (instancetype)shareInstance{
return sigdemo;
}
staticidsigdemo;
//放入load 保障只执行一次。。
+ (void)load{
sigdemo= [[selfalloc]init];
}
//alloc、new、都会调用此方法
+(instancetype)allocWithZone:(struct _NSZone *)zone{
if(sigdemo==nil) {
sigdemo= [superallocWithZone:zone];
}
return sigdemo;
}
//copyWithZone、mutableCopyWithZone拦截
- (id)copyWithZone:(NSZone*)zone{
NSLog(@"%s",__func__);
return sigdemo;
}
- (id)mutableCopyWithZone:(NSZone *)zone{
NSLog(@"%s",__func__);
return sigdemo;
}
GCD实现
//gcd实现
staticidsigdemo;
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t tocken;
dispatch_once(&tocken, ^{
if(sigdemo==nil) {
sigdemo= [superallocWithZone:zone];
}
});
return sigdemo;
}
+ (instancetype)sharedInstance
{
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
sigdemo= [[selfalloc]init];
});
return sigdemo;
}
- (id)copyWithZone:(NSZone*)zone
{
return sigdemo;
}
- (id)mutableCopyWithZone:(NSZone *)zone{
return sigdemo;
}