单例宏

作者: Elenx | 来源:发表于2017-01-22 01:07 被阅读21次

    使用方法:

    1. 声明了两个宏 SingleH(name) 和 SingleM(name) 两个宏
    2. 创建一个想要实现单例模式的类.在.h文件中包含单例宏文件
      #import<single.h>
    3. 在.h文件中使用SingleH(name)宏
      #import <Foundation/Foundation.h>
      #import <Single.h>
      @interface CustomClass : NSObject
      SingleH();
      @end
    4. 在.m文件中使用SingleM(name)宏
      #import "CustomClass.h"
      @implementation CustomClass
      SingleM(customClass);
      @end

    Single.h 文件

    #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/jpinbttx.html