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方法時(shí)獲取到的對象是相同的,但是當(dāng)我們通過alloc和init以及copy來構(gòu)造對象的時(shí)候俺孙,依然會創(chuàng)建新的實(shí)例。
要確保對象的唯一性掷贾,所以我們就需要封鎖用戶通過alloc和init以及copy來構(gòu)造對象這條道路睛榄。
我們知道,創(chuàng)建對象的步驟分為申請內(nèi)存(alloc)想帅、初始化(init)這兩個(gè)步驟场靴,我們要確保對象的唯一性,因此在第一步這個(gè)階段我們就要攔截它港准。當(dāng)我們調(diào)用alloc方法時(shí)旨剥,oc內(nèi)部會調(diào)用allocWithZone這個(gè)方法來申請內(nèi)存,我們覆寫這個(gè)方法浅缸,然后在這個(gè)方法中調(diào)用shareInstance方法返回單例對象轨帜,這樣就可以達(dá)到我們的目的●媒罚拷貝對象也是同樣的原理阵谚,覆寫copyWithZone方法蚕礼,然后在這個(gè)方法中調(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