单例是iOS开发中经常会用到的一种设计模式,顾名思义,即创建一个类,该类在整个程序的生命周期中只有一个实例对象,无论是通过new,alloc init,copy等方法创建,或者创建多少个对象,自始至终在内存中只会开辟一块空间,直到程序结束,由系统释放. 如下图用不同方式创建了6个对象,但通过打印其内存地址,我们可以发现它们是共享同一块内存空间的.
由于在平时开发中经常用到,所以我将创建单例的方法定义成宏,并封装成一个工具类,提供了一个类方法快速创建1个单例对象;并且该工具类的单例包括了在MRC模式下的创建方式,保证了在MRC模式下,仍能使用该工具类来快速创建1个单例对象;该工具类使用非常方便,只需在需要用到的类中导入头文件即可,以下是实现代码:
1 // 2 // YYSharedModelTool.h 3 // SharedModel 4 // 5 // Created by Arvin on 15/12/21. 6 // Copyright © 2015年 Arvin. All rights reserved. 7 // 8 9 #ifndef YYSharedModelTool_h 10 #define YYSharedModelTool_h 11 12 // .h 文件 13 // ##: 在宏中,表示拼接前后字符串 14 #define YYSharedModelTool_H(className) + (instancetype)shared##className; 15 16 #if __has_feature(objc_arc) // ARC 环境 17 18 // .m 文件 19 #define YYSharedModelTool_M(className)20 /****ARC 环境下实现单例的方法****/21 + (instancetype)shared##className {22 return [[self alloc] init];23 }24 25 - (id)copyWithZone:(nullable NSZone *)zone {26 return self;27 }28 29 + (instancetype)allocWithZone:(struct _NSZone *)zone {30 static id instance;31 static dispatch_once_t onceToken;32 dispatch_once(&onceToken, ^{33 instance = [super allocWithZone:zone];34 });35 return instance;36 } 37 38 #else // MRC 环境 39 40 // .m 文件 41 #define YYSharedModelTool_M(className)42 43 + (instancetype)shared##className {44 return [[self alloc] init];45 }46 47 - (id)copyWithZone:(nullable NSZone *)zone {48 return self;49 }50 51 + (instancetype)allocWithZone:(struct _NSZone *)zone {52 static id instance;53 static dispatch_once_t onceToken;54 dispatch_once(&onceToken, ^{55 instance = [super allocWithZone:zone];56 });57 return instance;58 }59 /****MRC 环境需要重写下面3个方法****/60 - (oneway void)release {61 62 }63 - (instancetype)retain {64 return self;65 }66 - (instancetype)autorelease {67 return self;68 } 69 70 #endif 71 72 #endif /* YYSharedModelTool_h */
end! 欢迎留言交流,一起学习...
原文:http://www.cnblogs.com/arvin-sir/p/5095037.html