美文网首页
单例的严谨写法

单例的严谨写法

作者: joyfulsad | 来源:发表于2016-04-12 17:09 被阅读0次

转载自http://www.jianshu.com/p/85618bcd4fee?utm_source=tuicool&utm_medium=referral

感谢Jingegehttp://www.jianshu.com/users/5dffd76b9caf


#import"Singleton.h"@implementationSingletonstaticSingleton* _instance = nil;

+(instancetype) shareInstance

{static dispatch_once_t onceToken ;

dispatch_once(&onceToken, ^{

_instance = [[superallocWithZone:NULL] init] ;

}) ;return_instance ;

}

+(id) allocWithZone:(struct _NSZone *)zone

{return[Singleton shareInstance] ;

}

-(id) copyWithZone:(struct _NSZone *)zone

{return[Singleton shareInstance] ;

}@end

我就问一个问题,如果我想销毁一个单列对象,需要怎么做?

喜欢(0)回复

Jingege@ysghome

1. 必须把static dispatch_once_t onceToken; 这个拿到函数体外,成为全局的.

2. +(void)attempDealloc{

onceToken = 0; // 只有置成0,GCD才会认为它从未执行过.它默认为0.这样才能保证下次再次调用shareInstance的时候,再次创建对象.

[_instance release];

_instance = nil;

}

相关文章

网友评论

      本文标题:单例的严谨写法

      本文链接:https://www.haomeiwen.com/subject/kukwlttx.html