iOS 建立一個在退出登陸時能夠銷燬的單例

1、單例簡介spa

單例模式是在軟件開發中常常用的一種模式。單例模式通俗的理解是,在整個軟件生命週期內,一個類只能有一個實例對象存在。指針

2、遇到的問題code

在平時開發使用單例的過程當中,有時候會有這樣的需求,在用戶登陸成功時,將用戶的信息記錄在用戶信息單例中,當用戶退出登陸後,由於這個用戶單例的指針被靜態存儲器的靜態變量引用着,致使用戶單例不能釋放,直到程序退出或者殺死後,內存才能被釋放。那有沒有一種方法可以在單例不須要的時候就釋放掉,而不要等到App結束呢?下面就介紹一種能夠銷燬的單例。對象

3、代碼blog

說的再多不如一句代碼來的實在,直接上代碼。生命週期

單例類以下所示:內存

SingletonTemplate.h文件開發

#import <Foundation/Foundation.h>

@interface SingletonTemplate : NSObject
/*!**生成單例***/
+ (instancetype)sharedSingletonTemplate;
/*!**銷燬單例***/
+ (void)destroyInstance;
@end

SingletonTemplate.m文件cmd

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));
}

 

4、代碼介紹it

關於代碼.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:----釋放了
相關文章
相關標籤/搜索