美文网首页
学习笔记 - 两行代码创建单例

学习笔记 - 两行代码创建单例

作者: 听雨花春风 | 来源:发表于2016-07-20 20:08 被阅读28次

    利用两行代码创建单例

    
    // 帮助实现单例设计模式
    
    // .h文件的实现
    #define SingletonH(methodName) + (instancetype)shared##methodName;
    
    // .m文件的实现
    #if __has_feature(objc_arc) // 是ARC
    #define SingletonM(methodName) \
    static id _instance = nil; \
    + (id)allocWithZone:(struct _NSZone *)zone \
    { \
    if (_instance == nil) { \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
    _instance = [super allocWithZone:zone]; \
    }); \
    } \
    return _instance; \
    } \
    \
    - (id)init \
    { \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
    _instance = [super init]; \
    }); \
    return _instance; \
    } \
    \
    + (instancetype)shared##methodName \
    { \
    return [[self alloc] init]; \
    } \
    + (id)copyWithZone:(struct _NSZone *)zone \
    { \
    return _instance; \
    } \
    \
    + (id)mutableCopyWithZone:(struct _NSZone *)zone \
    { \
    return _instance; \
    }
    
    #else // 不是ARC
    
    #define SingletonM(methodName) \
    static id _instance = nil; \
    + (id)allocWithZone:(struct _NSZone *)zone \
    { \
    if (_instance == nil) { \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
    _instance = [super allocWithZone:zone]; \
    }); \
    } \
    return _instance; \
    } \
    \
    - (id)init \
    { \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
    _instance = [super init]; \
    }); \
    return _instance; \
    } \
    \
    + (instancetype)shared##methodName \
    { \
    return [[self alloc] init]; \
    } \
    \
    - (oneway void)release \
    { \
    \
    } \
    \
    - (id)retain \
    { \
    return self; \
    } \
    \
    - (NSUInteger)retainCount \
    { \
    return 1; \
    } \
    + (id)copyWithZone:(struct _NSZone *)zone \
    { \
        return _instance; \
    } \
     \
    + (id)mutableCopyWithZone:(struct _NSZone *)zone \
    { \
        return _instance; \
    }
    
    #endif
    
    

    相关文章

      网友评论

          本文标题:学习笔记 - 两行代码创建单例

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