IOS單例的寫法

http://blog.sina.com.cn/s/blog_945590aa0102vxhb.html

Singleton.h
 
@interface Singleton : NSObject
 
+(instancetype) shareInstance ;
 
@end
 
 
 
#import "Singleton.h"
 
@implementation Singleton
 
static Singleton* _instance = nil;
 
+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init] ;
    }) ;
     
    return _instance ;
}
 
@end

可以看到,當(dāng)我們調(diào)用shareInstance方法時獲取到的對象是相同的,但是當(dāng)我們通過alloc和init以及copy來構(gòu)造對象的時候,依然會創(chuàng)建新的實(shí)例。
要確保對象的唯一性,所以我們就需要封鎖用戶通過alloc和init以及copy來構(gòu)造對象這條道路。
我們知道,創(chuàng)建對象的步驟分為申請內(nèi)存(alloc)、初始化(init)這兩個步驟,我們要確保對象的唯一性,因此在第一步這個階段我們就要攔截它。當(dāng)我們調(diào)用alloc方法時,oc內(nèi)部會調(diào)用allocWithZone這個方法來申請內(nèi)存,我們覆寫這個方法,然后在這個方法中調(diào)用shareInstance方法返回單例對象,這樣就可以達(dá)到我們的目的。拷貝對象也是同樣的原理,覆寫copyWithZone方法,然后在這個方法中調(diào)用shareInstance方法返回單例對象。

#import "Singleton.h"
@interface Singleton()<NSCopying,NSMutableCopying>
@end
 
@implementation Singleton
 
static Singleton* _instance = nil;
 
+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[super allocWithZone:NULL] init] ;
        //不是使用alloc方法,而是調(diào)用[[super allocWithZone:NULL] init] 
        //已經(jīng)重載allocWithZone基本的對象分配方法,所以要借用父類(NSObject)的功能來幫助出處理底層內(nèi)存分配的雜物
    }) ;
     
    return _instance ;
}
 
+(id) allocWithZone:(struct _NSZone *)zone
{
    return [Singleton shareInstance] ;
}
 
-(id) copyWithZone:(NSZone *)zone
{
    return [Singleton shareInstance] ;//return _instance;
}
 
-(id) mutablecopyWithZone:(NSZone *)zone
{
    return [Singleton shareInstance] ;
}
@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容