iOS中單例模式的兩種創(chuàng)建方法:GCD 和 @synchronize
1.GCD的方法
- 1.重寫allocWithZone:方法(注意不是重寫alloc方法,重寫了alloc 還是會(huì)執(zhí)行allocWithZone:)
- 2.為需要?jiǎng)?chuàng)建単例的類創(chuàng)建一個(gè)獲取単例的類方法
- 3.最后不要忘記重寫copyWithZone:
- 4.<NSCopying> 沒必要寫匹表,這邊只是為了快速敲出copyWithZone:方法
@interface JYPerson () //<NSCopying>
@end
@implementation JYPerson
static id _instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
+ (instancetype)sharedInstance
{
@synchronized(self) {
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
return _instance;
}
- (id)copyWithZone:(NSZone *)zone
{
return _instance;
}
2.GCD方法的宏實(shí)現(xiàn)
- 通過宏的方式省去一些不必要的代碼
- "" 是為了讓其預(yù)編譯指令了解是宏的內(nèi)容
// .h文件
#define JYSingletonH + (instancetype)sharedInstance;
// .m文件
#define JYSingletonM \
\
static id _instance; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
+ (instancetype)sharedInstance {\
\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
\
- (id)copyWithZone:(NSZone *)zone {\
\
return _instance;\
}
- 當(dāng)然有些為了定義単例的名字可以將參數(shù)傳入
// .h文件
#define JYSingletonH(name) + (instancetype)shared##name;
// .m文件
#define JYSingletonM(name) \
static id _instance; \
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
\
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instance; \
}
3.傳統(tǒng)寫法:
- 此方法需要注意的是線程安全(@synchronize)
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
@synchronized (self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
+ (instancetype)sharedInstance {
@synchronized (self) {
if (_instance == nil) {
_instance = [[self alloc] init];
}
}
return _instance;
}
- (id)copyWithZone:(NSZone *)zone {
return _instance;
}
4.注意事項(xiàng):
- 重構(gòu)GCD方法時(shí)采用的是宏方法门坷,估計(jì)有人也會(huì)想到(多個(gè)類想獲得單例)能否通過
繼承
來實(shí)現(xiàn)呢? - 答:是不能的桑孩,現(xiàn)在可以嘗試一下我定義兩個(gè)萬能類 teacher拜鹤, student 繼承于person,然后重寫単例方法流椒。
NSLog(@"%@ %@", [JYStudent sharedInstance], [[JYStudent alloc] init]);
NSLog(@"%@ %@", [JYTeacher sharedInstance], [[JYTeacher alloc] init]);
- 打印了上述方法會(huì)發(fā)現(xiàn)全都是
JYStudent
類的對(duì)象敏簿,然后換個(gè)順序:會(huì)全都是JYTeacher
類的對(duì)象,以 "static id _instance; "為例static
聲明的是一個(gè)全局變量的指針宣虾,所以指向也是同一塊地址惯裕。所以會(huì)出現(xiàn)誰在前面都是誰的對(duì)象