zoukankan      html  css  js  c++  java
  • iOS 单例模式

      单例:整个程序中只有一个实例,不论创建多少次,引用的都是同一个内存地址的对象

      以下是其实现方法,只要拷贝就可以直接用了(自己创建一个.h头文件,拷贝进去,调用的话在.h文件使用WYSSingletonH(这里写你的类名),然后在.m文件中调用WYSSingletonM(这里写你得类名),这里包括了ARC和MRC的实现):

    // .h文件
    #define WYSSingletonH(name)  +(instancetype)shared##name;
    
    // .m文件
    #if __has_feature(objc_arc)
    
        #define WYSSingletonM(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; 
        }
    
    #else
    
        #define WYSSingletonM(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
    欢迎加QQ群交流: iOS: 279096195 React Native: 482205185
  • 相关阅读:
    HTTP协议详解
    10本Linux免费电子书
    面试高级算法梳理笔记
    Linux服务器的那些性能参数指标
    2016 年开发者头条十大文章系列
    程序员如何优雅的挣零花钱
    [oracle] oracle权限传递
    [oracle] 两种权限:系统权限VS对象权限
    [oracle] 系统权限管理
    [oracle] 重要服务启动与停止命令行
  • 原文地址:https://www.cnblogs.com/GeekStar/p/4398135.html
Copyright © 2011-2022 走看看