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
  • 相关阅读:
    jquery.validate ajax提交
    linux权限不够,sh不能用
    几个简单的基类
    类型转换辅助工具类TypeCaseHelper
    linux下修改tomcat内存大小
    Hibernate,JPA注解@OneToMany_Map
    Hibernate,JPA注解@OneToMany_Set
    Hibernate,JPA注解@PrimaryKeyJoinColumn
    Hibernate,JPA注解@OneToOne_JoinColumn
    Hibernate,JPA注解@SecondaryTables
  • 原文地址:https://www.cnblogs.com/GeekStar/p/4398135.html
Copyright © 2011-2022 走看看