单例头文件

 1 // 帮助实现单例设计模式
 2 
 3 // .h文件的实现
 4 #define SingletonH(methodName) + (instancetype)shared##methodName;
 5 
 6 // .m文件的实现
 7 #if __has_feature(objc_arc) // 是ARC
 8 #define SingletonM(methodName) \
 9 static id _instace = nil; \
10 + (id)allocWithZone:(struct _NSZone *)zone \
11 { \
12 if (_instace == nil) { \
13 static dispatch_once_t onceToken; \
14 dispatch_once(&onceToken, ^{ \
15 _instace = [super allocWithZone:zone]; \
16 }); \
17 } \
18 return _instace; \
19 } \
20 \
21 - (id)init \
22 { \
23 static dispatch_once_t onceToken; \
24 dispatch_once(&onceToken, ^{ \
25 _instace = [super init]; \
26 }); \
27 return _instace; \
28 } \
29 \
30 + (instancetype)shared##methodName \
31 { \
32 return [[self alloc] init]; \
33 } \
34 + (id)copyWithZone:(struct _NSZone *)zone \
35 { \
36 return _instace; \
37 } \
38 \
39 + (id)mutableCopyWithZone:(struct _NSZone *)zone \
40 { \
41 return _instace; \
42 }
43 
44 #else // 不是ARC
45 
46 #define SingletonM(methodName) \
47 static id _instace = nil; \
48 + (id)allocWithZone:(struct _NSZone *)zone \
49 { \
50 if (_instace == nil) { \
51 static dispatch_once_t onceToken; \
52 dispatch_once(&onceToken, ^{ \
53 _instace = [super allocWithZone:zone]; \
54 }); \
55 } \
56 return _instace; \
57 } \
58 \
59 - (id)init \
60 { \
61 static dispatch_once_t onceToken; \
62 dispatch_once(&onceToken, ^{ \
63 _instace = [super init]; \
64 }); \
65 return _instace; \
66 } \
67 \
68 + (instancetype)shared##methodName \
69 { \
70 return [[self alloc] init]; \
71 } \
72 \
73 - (oneway void)release \
74 { \
75 \
76 } \
77 \
78 - (id)retain \
79 { \
80 return self; \
81 } \
82 \
83 - (NSUInteger)retainCount \
84 { \
85 return 1; \
86 } \
87 + (id)copyWithZone:(struct _NSZone *)zone \
88 { \
89     return _instace; \
90 } \
91  \
92 + (id)mutableCopyWithZone:(struct _NSZone *)zone \
93 { \
94     return _instace; \
95 }
96 
97 #endif

 

转载于:https://www.cnblogs.com/ndyBlog/p/3995774.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值