单例模式主要实现唯一实例,存活于整个程序范围内,一般存储用户信息经常用到单例,比如用户密码,密码在登录界面用一次,在修改密码界面用一次,而使用单例,就能保证密码唯一实例。如果不用单例模式,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 */