1)第一种方法
//当程序销毁时,静态变量也销毁,
static YuTian *yutian = nil;
+(YuTian *)shareInstance{
if (yutian == nil) {
yutian = [[YuTian alloc] init];
}
return yutian;
}
//为了防止 开发者 通过 alloc new来构建新对象,需要重写allocWithZone方法
+(id)allocWithZone:(NSZone *)zone{
if (yutian == nil) {
yutian = [[super allocWithZone:zone] init];
}
return yutian;
}
//为了防止通过copy产生新的实例对象,需要重写copy方法
-(id)copyWithZone:(NSZone *)zone{
return self;
}
//## 以下代码仅在非ARC环境下使用 ##
#if !__has_feature(objc_arc)
-(id)retain{
return self;
}
-(unsigned long)retainCount{
return NSIntegerMax;
}
-(void)release{
//空代码
}
-(void)autorelease{
return self;
}
#endif
2)第二种方法(使用 GCD 的方式 创建单例)
//当程序销毁时,静态变量也销毁,
static City *city = nil;
//使用 GCD 的方式 创建单例
+(instancetype)shareInstance{
//防止本方法被多次调用而引发冲突
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//此处的代码仅会被调用一次
city = [self new];
});
return city;
}
//如果允许另外使用alloc/new创建 非单例对象,则不必重写此方法
+(instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
city = [super allocWithZone:zone];
});
return city;
}









网友评论