单例 - 通过宏快速实现单例

创建一个.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 拼接参数使用##
#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
  • 当需要创建单例类时
    1.导入此文件
    2.在单例类的.h文件中
#import "singleton.h"
@interface DBTools : NSObject
singleton_h(单例的名称)
@end

3.在单例类的.m文件中

@implementation DBTools
singleton_m(单例的名称)
@end

这样就快速的实现了单例类,并且通过条件编译进行了MRC和ARC的判断,在不同内存管理模式下实现相应的方法

你可能感兴趣的:(单例 - 通过宏快速实现单例)