宏定义抽取单例

Posted on 2016-05-27 20:45  柠檬片  阅读(116)  评论(0)    收藏  举报
 1 #define SingleH(name) +(instancetype)share##name;
 2 
 3 #if __has_feature(objc_arc)
 4 //条件满足 ARC
 5 #define SingleM(name) static id _instance;\
 6 +(instancetype)allocWithZone:(struct _NSZone *)zone\
 7 {\
 8 static dispatch_once_t onceToken;\
 9 dispatch_once(&onceToken, ^{\
10 _instance = [super allocWithZone:zone];\
11 });\
12 \
13 return _instance;\
14 }\
15 \
16 +(instancetype)share##name\
17 {\
18 return [[self alloc]init];\
19 }\
20 \
21 -(id)copyWithZone:(NSZone *)zone\
22 {\
23 return _instance;\
24 }\
25 \
26 -(id)mutableCopyWithZone:(NSZone *)zone\
27 {\
28 return _instance;\
29 }
30 
31 #else
32 //MRC
33 #define SingleM(name) static id _instance;\
34 +(instancetype)allocWithZone:(struct _NSZone *)zone\
35 {\
36 static dispatch_once_t onceToken;\
37 dispatch_once(&onceToken, ^{\
38 _instance = [super allocWithZone:zone];\
39 });\
40 \
41 return _instance;\
42 }\
43 \
44 +(instancetype)share##name\
45 {\
46 return [[self alloc]init];\
47 }\
48 \
49 -(id)copyWithZone:(NSZone *)zone\
50 {\
51 return _instance;\
52 }\
53 \
54 -(id)mutableCopyWithZone:(NSZone *)zone\
55 {\
56 return _instance;\
57 }\
58 -(oneway void)release\
59 {\
60 }\
61 \
62 -(instancetype)retain\
63 {\
64     return _instance;\
65 }\
66 \
67 -(NSUInteger)retainCount\
68 {\
69     return MAXFLOAT;\
70 }
71 #endif
单例模式通用宏