iOS开发之自定义一个单例这里我使用宏:// .h#define single_interface(class) + (class *)shared##class;// .m// \ 代表下一行也属于宏// ## 是分隔符#define single_implementat ...
iOS开发之自定义一个单例
这里我使用宏:
// .h// .m//单例模式在ARC\MRC环境下的写法有所不同,需要编写2套不同的代码//重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)
- + (id)allocWithZone:(struct _NSZone *)zone
- {
- @synchronized(self) {
- if (!_instance) {
- _instance = [super allocWithZone:zone];
- }
- }
- return _instance;
- }
- //提供1个类方法让外界访问唯一的实例
- + (instancetype)shareInstance
- {
- @synchronized(self) {
- if (!_instance) {
- _instance = [[self alloc] init];
- }
- }
- return _instance;
- }
- //实现copyWithZone:方法
- + (id)copyWithZone:(struct _NSZone *)zone
- {
- return _instance;
- }
//非ARC中(MRC),单例模式的实现(比ARC多了几个步骤)
原标题:iOS开发之自定义一个单例
关键词:IOS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。