当前位置:首页 > 操作系统 > Ios

ios单例模式

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

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

            //
             .h文件
            #define WYSSingletonH(name)  +(instancetype)shared##name;

// .m文件#if __has_feature(objc_arc)

    #define WYSSingletonM(name)     staticid _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)     staticid _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 { return1;}     - (id)autorelease { return self;}

#endif

 

原文:http://www.cnblogs.com/GeekStar/p/4398135.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!