1互婿、首先捣郊,我們來了解一下什么是單例模式?單例模式是在整個(gè)應(yīng)用程序中只被初始化一次慈参,且是該類的唯一的實(shí)例呛牲。它的優(yōu)點(diǎn):易于外界訪問;費(fèi)時(shí)省內(nèi)存驮配;線程安全娘扩。缺點(diǎn):責(zé)任過重尊勿;不易擴(kuò)展;長時(shí)間未使用畜侦,系統(tǒng)會回收元扔,導(dǎo)致對象的狀態(tài)丟失。
2旋膳、代碼如下:
static XXXClass *_instance = nil;
+ (instancetype)shareInstance {
if (!_instance) {
_instance = [[super alloc] init];
}
return _instance;
}
//調(diào)用alloc方法時(shí)澎语,OC內(nèi)部會調(diào)用allocWithZone這個(gè)方法來申請內(nèi)存,此時(shí)我們可重寫此方法验懊。
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
//保證只初始化一次
dispatch_once(&onceToken, ^{
if (!_instance) {
_instance = [super allocWithZone:zone];
}
});
return _instance;
}
- (id)copy {
return _instance;
}
- (id)mutableCopy {
return _instance;
}
最后擅羞,為什么我們需要創(chuàng)建安全的單例模式呢?那是因?yàn)榉乐雇獠客ㄟ^alloc和init以及copy來構(gòu)造對象這種現(xiàn)象义图。
參考鏈接:https://blog.csdn.net/Nirvana_666/article/details/51854463
http://www.reibang.com/p/d07298613f86
http://blog.jimmyis.in/dispatch_once/