你的位置:首页 > 软件开发 > 操作系统 > 一句话实现OC单例模式

一句话实现OC单例模式

发布时间:2015-07-11 11:00:03
首先新建一个头文件,定义如下宏:// .h文件的实现#define SingletonH(methodName) + (instancetype)shared##methodName;// .m文件的实现#if __has_feature(objc_arc) // 是ARC#de ...

首先新建一个头文件,定义如下宏:

// .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

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:一句话实现OC单例模式

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录