OC - iOS - 宏单例

2016-08-04  本文已影响31人  黎希

Macro单例


// .h文件的实现

#define SingletonH(methodName) + (instancetype)shared##methodName;

// .m文件实现
#if __has_feature(objc_arc) // ARC下

#define SingletonM(methodName)\
static id _instance = nil;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
if (!_instance) {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
}\
return _instance;\
}\
\
- (instancetype)init{\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super init];\
});\
return _instance;\
}\
\
+ (instancetype)share##methodName{\
return [[self alloc] init];\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
return _instance;\
}\
+ (id)copyWithZone:(struct _NSZone *)zone {\
return _instance;\
}\
- (id)mutableCopyWithZone:(NSZone *)zone {\
return _instance;\
}\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone {\
return _instance;\
}

#else
// 非ARC下
#define SingletonM(methodName)\
static id _instance = nil;\
+ (instancetype)allocWithZone:(struct _NSZone *)zone{\
    if (!_instance) {\
        static dispatch_once_t onceToken;\
        dispatch_once(&onceToken, ^{\
            _instance = [super allocWithZone:zone];\
        });\
    }\
    return _instance;\
}\
\
- (instancetype)init{\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
        _instance = [super init];\
    });\
    return _instance;\
}\
\
+ (instancetype)share##methodName{\
    return [[self alloc] init];\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
return _instance;\
}\
+ (id)copyWithZone:(struct _NSZone *)zone {\
    return _instance;\
}\
- (id)mutableCopyWithZone:(NSZone *)zone {\
    return _instance;\
}\
+ (id)mutableCopyWithZone:(struct _NSZone *)zone {\
    return _instance;\
}\
- (oneway void)release{\
   \
}\
\
- (instancetype)retain{\
    return self;\
}\
\
- (NSUInteger)retainCount{\
    return 1;\
}

#endif

上一篇 下一篇

猜你喜欢

热点阅读