iOS 单例模式简单实例
程序员文章站
2022-05-03 11:46:13
单例模式主要实现唯一实例,存活于整个程序范围内,一般存储用户信息经常用到单例,比如用户密码,密码在登录界面用一次,在修改密码界面用一次,而使用单例,就能保证密码唯一实例。如果不用单例模式,init 两个的实例的堆栈地址不一样,所以存放的数据的位置也不一样,当其中一个数据改变,另一个数据依然不变。单例 ......
单例模式主要实现唯一实例,存活于整个程序范围内,一般存储用户信息经常用到单例,比如用户密码,密码在登录界面用一次,在修改密码界面用一次,而使用单例,就能保证密码唯一实例。如果不用单例模式,init 两个的实例的堆栈地址不一样,所以存放的数据的位置也不一样,当其中一个数据改变,另一个数据依然不变。单例模式的代码如下
.h文件
#ifndef singleton_h #define singleton_h @interface singleton : nsobject @property (nonatomic, copy) nsstring *pass; + (singleton *) sharedinstance; @end
.m文件
#import <foundation/foundation.h> #import "singleton.h" @implementation singleton static id sharedsingleton = nil; + (id)allocwithzone:(struct _nszone *)zone { if (sharedsingleton == nil) { static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ sharedsingleton = [super allocwithzone:zone]; }); } return sharedsingleton; } - (id)init { static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ sharedsingleton = [super init]; }); return sharedsingleton; } + (instancetype)sharedinstance { return [[self alloc] init]; } + (id)copywithzone:(struct _nszone *)zone { return sharedsingleton; } + (id)mutablecopywithzone:(struct _nszone *)zone { return sharedsingleton; } @end
宏实现单例
#ifndef singleton_m_h #define singleton_m_h // 帮助实现单例设计模式 // .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 /* singleton_m_h */
上一篇: golang日志收集方案之ELK
下一篇: iOS安全系列之一:HTTPS