使用方法:
- 1猎塞, 創(chuàng)建一個(gè)頭文件,然后黏貼如下代碼
//條件編譯
#if __has_feature(objc_arc)
//ARC
//.h頭文件中的單例宏
#define IMSingletonH(name) + (instancetype)shared##name;
//.m文件中的單例宏
#define IMSingletonM(name) \
static id _instance;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
+ (instancetype)shared##name{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
- (id)copyWithZone:(NSZone *)zone{\
return _instance;\
}
#else
//MRC
//.h頭文件中的單例宏
#define IMSingletonH(name) + (instancetype)shared##name;
//.m文件中的單例宏
#define IMSingletonM(name) \
static id _instance;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
+ (instancetype)shared##name{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
- (id)copyWithZone:(NSZone *)zone{\
return _instance;\
}\
- (oneway void)release{\
}\
- (instancetype)retain{\
return self;\
}\
- (NSUInteger)retainCount{\
return 1;\
}\
- (instancetype)autorelease{\
return self;\
}
#endif
- 2,在使用的時(shí)候只需要引入這個(gè)頭文件,然后在使用的那個(gè)頭文件和.m文件中各添加一句代碼即可寥殖,如下:
//注意下面括號(hào)中的內(nèi)容是你在用單例模式的時(shí)候顯示的名字,如sharedPlayer涩蜘;
//IMMusicPlayer *player03 = [IMMusicPlayer sharedPlayer];
//頭文件中
IMSingletonH(Player)
//.m文件中:
IMSingletonM(Player)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者