单例宏

作者: 闲得一B | 来源:发表于2016-06-22 23:15 被阅读13次

    文件名:Singleton.h

    // 以后就可以使用interfaceSingleton来替代后面的方法声明
    #define interfaceSingleton(name)  +(instancetype)share##name
    
    #if __has_feature(objc_arc)
    // ARC
    #define implementationSingleton(name)  \
    + (instancetype)share##name \
    { \
    name *instance = [[self alloc] init]; \
    return instance; \
    } \
    static name *_instance = nil; \
    + (instancetype)allocWithZone:(struct _NSZone *)zone \
    { \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
    _instance = [[super allocWithZone:zone] init]; \
    }); \
    return _instance; \
    } \
    - (id)copyWithZone:(NSZone *)zone{ \
    return _instance; \
    } \
    - (id)mutableCopyWithZone:(NSZone *)zone \
    { \
    return _instance; \
    }
    #else
    // MRC
    
    #define implementationSingleton(name)  \
    + (instancetype)share##name \
    { \
    name *instance = [[self alloc] init]; \
    return instance; \
    } \
    static name *_instance = nil; \
    + (instancetype)allocWithZone:(struct _NSZone *)zone \
    { \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
    _instance = [[super allocWithZone:zone] init]; \
    }); \
    return _instance; \
    } \
    - (id)copyWithZone:(NSZone *)zone{ \
    return _instance; \
    } \
    - (id)mutableCopyWithZone:(NSZone *)zone \
    { \
    return _instance; \
    } \
    - (oneway void)release \
    { \
    } \
    - (instancetype)retain \
    { \
    return _instance; \
    } \
    - (NSUInteger)retainCount \
    { \
    return  MAXFLOAT; \
    }
    #endif
    

    斜杠是为了连接宏
    ##是为了让后面的name能被替换


    实现实例:

    #import <Foundation/Foundation.h>
    #import "Singleton.h"
    @interface Person : NSObject
    interfaceSingleton(Person);
    @end
    
    #import "Person.h"
    @implementation Person
    implementationSingleton(Person)
    @end
    

    assert();断言

    相关文章

      网友评论

          本文标题:单例宏

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