單例模式:
在程序運(yùn)行過程中,一個(gè)類只有一個(gè)實(shí)例.
作用:1.可以保證在程序運(yùn)行過程中,一個(gè)類只有一個(gè)實(shí)例,而且該實(shí)例易于供外界訪問.
2.方便控制實(shí)例個(gè)數(shù),節(jié)省系統(tǒng)資源.
alloc和allocWithZone
在初始化的時(shí)候會(huì)調(diào)用alloc init,alloc分配內(nèi)存空間,init是初始化.給對(duì)象分配內(nèi)存空間除了alloc還有allocWithZone.使用alloc初始化一個(gè)類的實(shí)例時(shí),默認(rèn)是調(diào)用allocWithZone.
如果不重寫allocWithZone方法,實(shí)際上是沒有實(shí)現(xiàn)單例.
不完全的單例模式,只重寫了allocWithZone.
條件編譯,用來判斷當(dāng)前的項(xiàng)目環(huán)境.
if __has_feature(objc_arc)
NSLog(@"arc");
else
NSLog(@"mrc");
endif
實(shí)現(xiàn)單例模式,新建一個(gè)工具類.
>1.提供一個(gè)類方法,方便外界調(diào)用. 命名規(guī)范share+類名.
2.提供一個(gè)靜態(tài)變量,強(qiáng)引用著已經(jīng)實(shí)例化的單例對(duì)象實(shí)例.
static ShareTool *_instance;
3.重寫allocWithZone
使用一次性代碼.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
3.提供類方法方便訪問
+(instancetype)shareDownloadTool
{
return [[self alloc]init];
}
4. 重寫copy
-(id)copyWithZone:(NSZone *)zone
{
return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone
{
return _instance;
}