美文网首页
OC - iOS - 宏单例

OC - iOS - 宏单例

作者: 黎希 | 来源:发表于2016-08-04 11:19 被阅读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
    
    

    相关文章

      网友评论

          本文标题:OC - iOS - 宏单例

          本文链接:https://www.haomeiwen.com/subject/fpkzdttx.html