美文网首页
用宏封装单例

用宏封装单例

作者: yzu | 来源:发表于2015-11-29 22:55 被阅读45次

    <pre>#define SingletoH(methodName) +(instancetype)shared##methodName;//.h文件里实现

    //.m文件里面实现

    if __has_feature(objc_arc)//ARC情况下

    define SingletoM(methodName) \

    static __strong id _instace=nil;\

    • (instancetype)allocWithZone:(struct _NSZone *)zone
      {
      if (_instace==nil) {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
      _instace=[super allocWithZone:zone];
      });
      }
      return _instace;
      }\
    • (instancetype)init
      {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
      _instace = [super init];
      });
      return _instace;
      }\
    • (instancetype)shared##methodName
      {
      return [[self alloc] init];
      }

    else//非ARC情况下

    define SingletoM(methodName) \

    static id *_instace=nil;\

    • (instancetype)allocWithZone:(struct _NSZone *)zone
      {
      if (_instace==nil) {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
      _instace=[super allocWithZone:zone];
      });
      }
      return _instace;
      }\
    • (instancetype)init
      {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
      _instace = [super init];
      });
      return _instace;
      }\
    • (instancetype)shared##methodName
      {
      return [[self alloc] init];
      }\
    • (oneway void)release
      {
      }\
    • (instancetype)retain
      {
      return self;
      }\
    • (NSUInteger)retainCount
      {
      return 1;
      }

    endif

    </pre>

    相关文章

      网友评论

          本文标题:用宏封装单例

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