創(chuàng)建一個.h文件,代碼如下:
#ifdef __has_feature(objc_arc) // ARC模式下
//.h文件
#define singleton_h(name) +(instancetype)sharad##name;
//.m文件
#define singleton_m(name) static id _instanceType = nil;\
+(instancetype)sharad##name\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instanceType = [[self alloc]init];\
});\
return _instanceType;\
}\
+ (instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instanceType = [super allocWithZone:zone];\
});\
return _instanceType;\
}\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instanceType;\
}
#else //MRC模式下
//.h 拼接參數(shù)使用##
#define singleton_h(name) +(instancetype)sharad##name;
//.m 宏里面換行
#define singleton_m(name) static id _instanceType = nil;\
+(instancetype)sharad##name\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instanceType = [[self alloc]init];\
});\
return _instanceType;\
}\
+ (instancetype)allocWithZone:(struct _NSZone *)zone\
{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instanceType = [super allocWithZone:zone];\
});\
return _instanceType;\
}\
-(id)copyWithZone:(NSZone *)zone\
{\
return _instanceType;\
}\
-(oneway void)release\
{\
\
}\
-(instancetype)retain\
{\
return _instanceType;\
}\
-(instancetype)autorelease\
{\
return _instanceType;\
}\
- (NSUInteger)retainCount\
{\
return 1;\
}
#endif
- 當(dāng)需要創(chuàng)建單例類時
1.導(dǎo)入此文件
2.在單例類的.h文件中
#import "singleton.h"
@interface DBTools : NSObject
singleton_h(單例的名稱)
@end
3.在單例類的.m文件中
@implementation DBTools
singleton_m(單例的名稱)
@end
這樣就快速的實現(xiàn)了單例類,并且通過條件編譯進(jìn)行了MRC和ARC的判斷,在不同內(nèi)存管理模式下實現(xiàn)相應(yīng)的方法