单例宏

作者: Yasin的简书 | 来源:发表于2016-01-23 16:53 被阅读179次
    #define DEFINE_SINGLETON_HEADER(className) \  
    \  
    + (className *)shared##className;  
      
    #define DEFINE_SINGLETON_IMPLEMENTATION(className) \  
    \  
    static className *shared##className = nil; \  
    static dispatch_once_t pred; \  
    \  
    + (className *)shared##className { \  
        dispatch_once(&pred, ^{ \  
            shared##className = [[super allocWithZone:NULL] init]; \  
        }); \  
        return shared##className; \  
    } \  
    \  
    + (id)allocWithZone:(NSZone *)zone { \  
        return [self shared##className];\  
    } \  
    \  
    - (id)copyWithZone:(NSZone *)zone { \  
    return self; \  
    }  
    

    使用如下

    @interface MySingleton : NSObject  
    DEFINE_SINGLETON_HEADER(MySingleton);  
    /**other method declare**/  
    @end  
    

    比如

    @implementation MySingleton  
    DEFINE_SINGLETON_IMPLEMENTATION(MySingleton)  
      
    - (instancetype)init {  
        if (sharedMySingleton) {  
            return sharedMySingleton;  
        }  
        if (self = [super init]) {  
            //todo init other  
        }  
        return self;  
    }  
    @end  
    

    相关文章

      网友评论

          本文标题:单例宏

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