其实在OC中有好多单例的例子例如 [UIApplication sharedApplication];
[NSUserDefaults standardUserDefaults]; ......还有很多 废话不多说,直接上代码 - // .h文件的实现
- //定义一个宏 shared##methodName 加## 是为了能够更改methodName方法体名称
- #define SingletonH(methodName) + (instancetype)shared##methodName;
- // .m文件的实现
- #if __has_feature(objc_arc) // 是ARC,这里判断的是ARC还是非ARC
- #define SingletonM(methodName) \
- static id _instace = nil; \
- + (id)allocWithZone:(struct _NSZone *)zone \//重写allocWithZone方法
- { \
- if (_instace == nil) { \//懒加载
- static dispatch_once_t onceToken; \//保证实例化出来的对象的唯一性
- dispatch_once(&onceToken, ^{ \
- _instace = [super allocWithZone:zone]; \//调用父类的allocWithZone方法
- }); \
- } \
- return _instace; \//返回实例
- } \
- \
- - (id)init \//重写ini方法
- { \
- 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 \//重写copyWithZone方
- { \
- return _instace; \
- } \
- \
- + (id)mutableCopyWithZone:(struct _NSZone *)zone \//重写mutableCopyWithZone方法
- { \
- 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 \//镂空release方法,保证对象的计数器一直为1,
- { \
- } \
- - (id)retain \//重写retain方法
- { \
- return self; \
- } \
- - (NSUInteger)retainCount \//重写retainCount方法
- { \
- return 1; \
- } \
- + (id)copyWithZone:(struct _NSZone *)zone \
- { \
- return _instace; \
- } \
- + (id)mutableCopyWithZone:(struct _NSZone *)zone \
- { \
- return _instace; \
- }
- #endif
直接上图吧
|