码迷,mamicode.com
首页 > 移动开发 > 详细

iOS开发之单例头文件

时间:2015-12-04 12:57:09      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

// 帮助实现单例设计模式

// .h文件的实现
#define SingletonH(methodName) + (instancetype)shared##methodName;

// .m文件的实现
#if __has_feature(objc_arc) // 是ARC
#define SingletonM(methodName) static id _instace = nil; + (id)allocWithZone:(struct _NSZone *)zone { if (_instace == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super allocWithZone:zone]; }); } return _instace; } - (id)init { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super init]; }); return _instace; } + (instancetype)shared##methodName { return [[self alloc] init]; } + (id)copyWithZone:(struct _NSZone *)zone { return _instace; } + (id)mutableCopyWithZone:(struct _NSZone *)zone { return _instace; }

#else // 不是ARC

#define SingletonM(methodName) static id _instace = nil; + (id)allocWithZone:(struct _NSZone *)zone { if (_instace == nil) { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super allocWithZone:zone]; }); } return _instace; } - (id)init { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instace = [super init]; }); return _instace; } + (instancetype)shared##methodName { return [[self alloc] init]; } - (oneway void)release { } - (id)retain { return self; } - (NSUInteger)retainCount { return 1; } + (id)copyWithZone:(struct _NSZone *)zone {     return _instace; }  + (id)mutableCopyWithZone:(struct _NSZone *)zone {     return _instace; }

#endif

将上述代码放进放到.h头文件中

使用方法:在单例的文件中,.h中实现SingletonH(mothodName)(methodName为方法名)

              .m中实现SingletonM(mothodName)

iOS开发之单例头文件

标签:

原文地址:http://www.cnblogs.com/wuhongxing/p/5018899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!