一、單例簡介
單例模式是在軟件開發中經常用的一種模式。單例模式通俗的理解是,在整個軟件生命周期內,一個類只能有一個實例對象存在。
二、遇到的問題
在平時開發使用單例的過程中,有時候會有這樣的需求,在用戶登錄成功時,將用戶的信息記錄在用戶信息單例中,當用戶退出登錄后,因為這個用戶單例的指針被靜態存儲器的靜態變量引用着,導致用戶單例不能釋放,直到程序退出或者殺死后,內存才能被釋放。那有沒有一種方法能夠在單例不需要的時候就釋放掉,而不要等到App結束呢?下面就介紹一種可以銷毀的單例。
三、代碼
說的再多不如一句代碼來的實在,直接上代碼。
單例類如下所示:
SingletonTemplate.h文件
#import <Foundation/Foundation.h> @interface SingletonTemplate : NSObject /*!**生成單例***/ + (instancetype)sharedSingletonTemplate; /*!**銷毀單例***/ + (void)destroyInstance; @end
SingletonTemplate.m文件
static SingletonTemplate *_instance=nil; @implementation SingletonTemplate + (instancetype)sharedSingletonTemplate { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance=[[self alloc] init]; NSLog(@"%@:----創建了",NSStringFromSelector(_cmd)); }); return _instance; } + (instancetype)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [super allocWithZone:zone]; }); return _instance; } + (void)destroyInstance { _instance=nil; } - (id)copyWithZone:(NSZone *)zone { return _instance; } - (void)dealloc { NSLog(@"%@:----釋放了",NSStringFromSelector(_cmd)); }
四、代碼介紹
關於代碼.h文件中有兩個方法,一個是生成單例,另一個是銷毀單例;其中銷毀單例方法,是將靜態存儲區的靜態變量指針置為nil,這樣單例對象在沒有任何指針指向的情況下被系統回收了。
運行程序,打印的結果如下
- (void)viewDidLoad { [super viewDidLoad]; [SingletonTemplate sharedSingletonTemplate]; sleep(2); [SingletonTemplate destroyInstance]; } 打印結果: 2017-02-27 22:42:33.915 MyTestWorkProduct[3550:78078] sharedSingletonTemplate:----創建了 2017-02-27 22:42:35.990 MyTestWorkProduct[3550:78078] dealloc:----釋放了