• 一句话实现OC单例模式


    首先新建一个头文件,定义如下宏:

    // .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
    

    然后在你定义单例类的

    .h 文件 写 SingletonH(MyMethodName) 

    .m 文件写 SingletonM(MyMethodName)

    搞定!

  • 相关阅读:
    HDU 1828 Picture (线段树:扫描线周长)
    [USACO18OPEN] Multiplayer Moo (并查集+维护并查集技巧)
    NOIP2016 天天爱跑步 (树上差分+dfs)
    NOIP2013 华容道 (棋盘建图+spfa最短路)
    NOIP2015 运输计划 (树上差分+二分答案)
    NOIP2018 前流水账
    luogu P2331 [SCOI2005]最大子矩阵
    luogu P2627 修剪草坪
    CF101D Castle
    luogu P2473 [SCOI2008]奖励关
  • 原文地址:https://www.cnblogs.com/hoyawolfer/p/4638114.html
Copyright © 2020-2023  润新知