以下是我實(shí)現(xiàn)單例類的兩個(gè)方案,并且每個(gè)方案都經(jīng)過了性能優(yōu)化,如下:
方案1:互斥鎖
通過互斥鎖實(shí)現(xiàn)的單列代碼;不保證只初始化一次!
//此單例方案不能保證只初始一次
//單例指針
static id _instance = nil;
+ (instancetype)sharedInstance
{
if (_instance == nil) { //因?yàn)榧渔i操作要比普通操作耗費(fèi)更多的資源赢赊,所以盡量把鎖內(nèi)的執(zhí)行條件在加鎖之前先判斷一次,以減少不必根的加鎖操作
@synchronized(self) {
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
}
return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
if (_instance == nil) { //因?yàn)榧渔i操作要比普通操作耗費(fèi)更多的資源级历,所以盡量把鎖內(nèi)的執(zhí)行條件在加鎖之前先判斷一次释移,以減少不必根的加鎖操作
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
}
return _instance;
}
//copy在底層 會(huì)調(diào)用copyWithZone:
-(id)copyWithZone:(NSZone*)zone {
return _instance;
}
+(id)copyWithZone:(struct _NSZone *)zone {
return _instance;
}
//mutableCopy在底層 會(huì)調(diào)用mutableCopyWithZone:
-(id)mutableCopyWithZone:(NSZone*)zone {
return _instance;
}
+ (id)mutableCopyWithZone:(struct _NSZone *)zone{
return _instance;
}
方案2:GCD
通過GCD方式實(shí)現(xiàn)的單列代碼
//單列指針
static id _instance = nil;
//獲取共享單列
+(instancetype)sharedInstance {
return [[self alloc] init];
}
//alloc方法會(huì)調(diào)用allocWithZone
+(instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//只執(zhí)行一次
_instance = [super allocWithZone: zone];
});
return _instance;
}
//初始化方法
-(instancetype)init {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//只執(zhí)行一次
_instance = [super init];
});
return _instance;
}
//copy在底層 會(huì)調(diào)用copyWithZone:
-(id)copyWithZone:(NSZone*)zone {
return _instance;
}
+(id)copyWithZone:(struct _NSZone *)zone {
return _instance;
}
//mutableCopy在底層 會(huì)調(diào)用mutableCopyWithZone:
-(id)mutableCopyWithZone:(NSZone*)zone {
return _instance;
}
+ (id)mutableCopyWithZone:(struct _NSZone *)zone{
return _instance;
}