一般情況我們都是這么寫:
static MySingleton *shareSingleton;
+( instancetype ) sharedSingleton? {
static? dispatch_once? onceToken;
dispatch_once ( &onceToken, ^ {
shareSingleton = [ [ MySingleton alloc ] init ] ;
} );
return?sharedSingleton;
}
但是調(diào)用shareInstance方法時獲取到的對象是相同的,但是當我們通過alloc和init來構(gòu)造對象的時候,有時候得到的對象卻是不一樣的。創(chuàng)建對象的步驟分為申請內(nèi)存(alloc)、初始化(init)這兩個步驟,我們要確保對象的唯一性,因此在第一步這個階段我們就要攔截它。當我們調(diào)用alloc方法時,oc內(nèi)部會調(diào)用allocWithZone這個方法來申請內(nèi)存,我們覆寫這個方法,然后在這個方法中調(diào)用shareInstance方法返回單例對象,這樣就可以達到我們的目的。拷貝對象也是同樣的原理,覆寫copyWithZone方法,然后在這個方法中調(diào)用shareInstance方法返回單例對象。所以建議以后安全一點都這么寫:
static? MySingleton? *shareSingleton = nil;
+( instancetype ) sharedSingleton? {
static? dispatch_once? onceToken;
dispatch_once ( &onceToken, ^ {
shareSingleton? =? [[super allocWithZone:NULL] init] ;
} );
return?sharedSingleton;
}
+(id) allocWithZone:(struct _NSZone *)zone {
return [Singleton shareInstance] ;
}
-(id) copyWithZone:(struct _NSZone *)zone {
return [Singleton shareInstance] ;
}