zoukankan      html  css  js  c++  java
  • 非ARC和ARC下创建单利模式的宏定义,可以直接套用

    本例子是将创建单例模式的.h和.m文件抽出来,用一个宏来定义,放在头文件中:

    // 帮助实现单例设计模式
    
    // .h文件的实现
    #define SingletonH(methodName) + (instancetype)shared##methodName;
    
    // .m文件的实现
    #if __has_feature(objc_arc) // 是ARC
    #define SingletonM(methodName) 
    static id _instace = nil; 
    + (id)allocWithZone:(struct _NSZone *)zone 
    { 
    if (_instace == nil) { 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    _instace = [super allocWithZone:zone]; 
    }); 
    } 
    return _instace; 
    } 
    
    - (id)init 
    { 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    _instace = [super init]; 
    }); 
    return _instace; 
    } 
    
    + (instancetype)shared##methodName 
    { 
    return [[self alloc] init]; 
    } 
    + (id)copyWithZone:(struct _NSZone *)zone 
    { 
    return _instace; 
    } 
    
    + (id)mutableCopyWithZone:(struct _NSZone *)zone 
    { 
    return _instace; 
    }
    
    #else // 不是ARC
    
    #define SingletonM(methodName) 
    static id _instace = nil; 
    + (id)allocWithZone:(struct _NSZone *)zone 
    { 
    if (_instace == nil) { 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    _instace = [super allocWithZone:zone]; 
    }); 
    } 
    return _instace; 
    } 
    
    - (id)init 
    { 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    _instace = [super init]; 
    }); 
    return _instace; 
    } 
    
    + (instancetype)shared##methodName 
    { 
    return [[self alloc] init]; 
    } 
    
    - (oneway void)release 
    { 
    
    } 
    
    - (id)retain 
    { 
    return self; 
    } 
    
    - (NSUInteger)retainCount 
    { 
    return 1; 
    } 
    + (id)copyWithZone:(struct _NSZone *)zone 
    { 
        return _instace; 
    } 
     
    + (id)mutableCopyWithZone:(struct _NSZone *)zone 
    { 
        return _instace; 
    }
    
    #endif
    
  • 相关阅读:
    实现三栏布局
    Element对象
    React中组件间通信的方式
    CSS实现展开动画
    Vue中组件间通信的方式
    java面试一日一题:mysql执行delete数据真的被删除了吗
    java面试一日一题:讲对mysql的MVCC的理解
    java面试一日一题:讲下mysql中的锁
    java面试一日一题:如何优化sql
    java面试一日一题:在创建微服务时,是用RPC还是http
  • 原文地址:https://www.cnblogs.com/angongIT/p/3821783.html
Copyright © 2011-2022 走看看