大概12年還在學(xué)習(xí)iOS再悼,之后轉(zhuǎn)戰(zhàn)cocos unity,但到ios端始終會(huì)見到OC鸠匀。單例模式一直用的非常古老的懶加載,最近重新復(fù)習(xí)了一下OC記錄一下。
首先了解一下instancetype 與id的相同與區(qū)別。
相同點(diǎn):都是萬能指針宵距,指向?qū)ο?/p>
不同點(diǎn):?
1.id在編譯的時(shí)候不能判斷對(duì)象的真實(shí)類型,instancetype在編譯的時(shí)候可以判斷對(duì)象的真實(shí)類型
2.id可以用來定義變量吨拗,可以作為返回值類型满哪,可以作為形參類型;instancetype只能作為返回值類型
1.懶加載(現(xiàn)在已經(jīng)不推薦這種方法了丢胚,線程不安全)
#import?"SingletonVC.h"
static?SingletonVC?*?_singletonVC;
@implementation?SingletonVC
+?(instancetype)allocWithZone:(struct?_NSZone?*)zone{
????if(_singletonVC?==?nil)?{
????????_singletonVC?=?[superallocWithZone:zone];
????}
????return_singletonVC;
}
+?(instancetype)share{
????return[[self?alloc]?init];}
@end
2.GCD的一次函數(shù)
#import "single.h"
staticsingle*_singleVC;
@implementation single
+(instancetype)allocWithZone:(struct_NSZone*)zong
{
? ? staticdispatch_once_tonceToken;
? ? dispatch_once(&onceToken, ^{
? ? ? ? if(_singleVC==nil)
? ? ? ? {
? ? ? ? ? ? _singleVC= [superallocWithZone:zong];
? ? ? ? }
? ? });
? ? return _singleVC;
}
+(instancetype)share
{
? ? return[[selfalloc]init];
}
@end
3.線程鎖
#import?"SingletonVC.h"
static?SingletonVC?*?_singletonVC;
@implementation?SingletonVC
+?(instancetype)allocWithZone:(struct?_NSZone?*)zone{
????@synchronized?(self)?{
????????if(_singletonVC?==?nil)?{
????????????_singletonVC?=?[superallocWithZone:zone];
????????}
????}
????return_singletonVC;
}
+?(instancetype)share{
????return[[self?alloc]?init];
}
@end