单例是iOS开发中常常会用到的一种设计模式,顾名思义,即建立一个类,该类在整个程序的生命周期中只有一个实例对象,不管是经过new,alloc init,copy等方法建立,或者建立多少个对象,自始至终在内存中只会开辟一块空间,直到程序结束,由系统释放.设计模式
以下图用不一样的方式建立6个对象,但经过打印其内存地址,咱们能够发现它们是共享同一块内存空间的.工具
因为在平时开发中常常用到,因此我将建立单例的方法定义成宏,并封装成一个工具类,提供了一个类方法来快速建立1个单例对象;学习
而且此类的单例包括了在MRC模式下的建立方式,保证了在MRC模式下,仍能使用该工具类来快速建立1个单例对象;spa
该工具类使用很是方便,只需在须要用到的类中导入头文件便可,如下是实现代码:设计
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! 欢迎留言交流,一块儿学习...code