美文网首页
iOS 单例宏定义记录

iOS 单例宏定义记录

作者: Her0cheN | 来源:发表于2020-03-23 23:20 被阅读0次

    MYSingleton.h : 单例宏定义 - 头文件

    // 使用方法:.h 添加
    // MYSingletonH(SingletonClass)//单例模式
    // 使用方法:.m 添加
    // MYSingletonM(SingletonClass)//单例模式
    
    
    // MYSingletonH.h文件 - 创建MYSingletonH.h全局文件
    #define MYSingletonH(name) + (instancetype)shared##name;
    
    #if __has_feature(objc_arc)
    
        #define MYSingletonM(name) \
        static id _instace; \
     \
        + (id)allocWithZone:(struct _NSZone *)zone \
        { \
            if (_instace == nil) {\
                _instace = [super allocWithZone:zone]; \
                NSLog(@"单例创建!--- 上架删除该行"); \
            } \
            return _instace; \
        } \
     \
        + (instancetype)shared##name \
        { \
            if (_instace == nil) {\
                _instace = [[self alloc]init]; \
            } \
          return _instace; \
      \
        } \
     \
        - (id)copyWithZone:(NSZone *)zone \
        { \
            return _instace; \
        }
    
    #else
    
        #define MYSingletonM(name) \
        static id _instace; \
     \
        + (id)allocWithZone:(struct _NSZone *)zone \
        { \
            static dispatch_once_t onceToken; \
            dispatch_once(&onceToken, ^{ \
                _instace = [super allocWithZone:zone]; \
            }); \
            return _instace; \
        } \
     \
        + (instancetype)shared##name \
        { \
            static dispatch_once_t onceToken; \
            dispatch_once(&onceToken, ^{ \
                _instace = [[self alloc] init]; \
            }); \
            return _instace; \
        } \
     \
        - (id)copyWithZone:(NSZone *)zone \
        { \
            return _instace; \
        } \
     \
        - (oneway void)release { } \
        - (id)retain { return self; } \
        - (NSUInteger)retainCount { return 1;} \
        - (id)autorelease { return self;}
    
    #endif
    
    

    相关文章

      网友评论

          本文标题:iOS 单例宏定义记录

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