【iOS开发系列】单例模式宏(兼容ARC和非ARC)
2015-06-24 19:28
591 查看
实现单例模式。这种代码完全不需要自己写的,只要拷贝就好了。在这里分享一下。
/** * ##:连接字符串和参数 */ #define singleton_h(name) + (instancetype)shared##name; /** * 【 ARC】环境 */ #if __has_feature(objc_arc) #define singleton_m(name) \ \ static id _instance; \ \ + (id)allocWithZone:(struct _NSZone *)zone \ { \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken, ^{ \ _instance = [super allocWithZone:zone]; \ }); \ return _instance; \ } \ \ \ + (instancetype)shared##name \ { \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken,^{ \ _instance = [[self alloc] init]; \ }); \ return _instance; \ } \ \ + (id)copyWithZone:(struct _NSZone *)zone \ { \ return _instance; \ } /** * 非【 ARC】环境 */ #else #define singleton_m(name) \ static id _instance; \ \ + (id)allocWithZone:(struct _NSZone *)zone \ { \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken, ^{ \ _instance = [super allocWithZone:zone]; \ }); \ return _instance; \ } \ \ \ + (instancetype)shared##name \ { \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken,^{ \ _instance = [[self alloc] init]; \ }); \ return _instance; \ } \ \ - (oneway void)release \ { \ \ } \ \ - (id)autorelease \ { \ return _instance; \ } \ \ - (id)retain \ { \ return _instance; \ } \ \ - (id)retainCount \ { \ return 1; \ } \ \ + (id)copyWithZone:(struct _NSZone *)zone \ { \ return _instance; \ } #endif
相关文章推荐
- iOS-KVC究竟怎么用
- IOS知识点小结
- 为iOS(iPhone)开发环境编译OpenSSL库
- 【iOS开发系列】常用的第三方库
- IOS 开发学习37 的Architecture与iphone版本对应关系
- 【iOS开发系列】多线程开发
- IOS项目之分层MVVM
- iOS NSThread 的三种创建线程的方法 非常简单好用
- IOS--OC--LessonProperty 属性 点语法
- Cordova+ ios 插件开发
- OC基础:属性.点语法.KVC 分类: ios学习 OC 2015-06-24 17:24 61人阅读 评论(0) 收藏
- 【iOS开发】多屏尺的自动适配 AutoLayout (纯代码方式)
- iOS 延时执行(OC)
- iOS中使用.plist文件延迟读取的方法(续)
- iOS 系统地图实现及定位
- iOS学习010
- ios中纯手写代码怎么实现内容的自动布局
- mac ox mountain lion+xcode4.5 编译 boost for ios
- iOS进阶——可取消的block
- iOS中使用.plist文件延迟读取的方法