单例

作者: _iceCoke | 来源:发表于2017-08-16 10:10 被阅读0次

    单例

    static Class *manager;
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            if (manager == nil) {
                manager = [super allocWithZone:zone];
            }
        });
        return manager;
    }
    + (instancetype)manager {
        return [[self alloc]init];
    }
    - (instancetype)copyWithZone:(NSZone *)zone {
        return manager;
    }
    - (instancetype)mutableCopyWithZone:(NSZone *)zone {
        return manager;
    }
    
    
    

    单例宏

    #define SingleH(name) +(instancetype)share##name;
    
    #if __has_feature(objc_arc)
    //条件满足 ARC
    #define SingleM(name) static id _instance;\
    +(instancetype)allocWithZone:(struct _NSZone *)zone\
    {\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
    _instance = [super allocWithZone:zone];\
    });\
    \
    return _instance;\
    }\
    \
    +(instancetype)share##name\
    {\
    return [[self alloc]init];\
    }\
    \
    -(id)copyWithZone:(NSZone *)zone\
    {\
    return _instance;\
    }\
    \
    -(id)mutableCopyWithZone:(NSZone *)zone\
    {\
    return _instance;\
    }
    
    #else
    //MRC
    #define SingleM(name) static id _instance;\
    +(instancetype)allocWithZone:(struct _NSZone *)zone\
    {\
    static dispatch_once_t onceToken;\
    dispatch_once(&onceToken, ^{\
    _instance = [super allocWithZone:zone];\
    });\
    \
    return _instance;\
    }\
    \
    +(instancetype)share##name\
    {\
    return [[self alloc]init];\
    }\
    \
    -(id)copyWithZone:(NSZone *)zone\
    {\
    return _instance;\
    }\
    \
    -(id)mutableCopyWithZone:(NSZone *)zone\
    {\
    return _instance;\
    }\
    -(oneway void)release\
    {\
    }\
    \
    -(instancetype)retain\
    {\
        return _instance;\
    }\
    \
    -(NSUInteger)retainCount\
    {\
        return MAXFLOAT;\
    }
    #endif
    

    相关文章

      网友评论

          本文标题:单例

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