創建單例的正確姿勢
阿新 • • 發佈:2017-11-24
attribute ati tro margin 直接 tab amp har ron
方法 1:
聲明 :+ (instancetype)sharedInstance 單例方法
重寫:+ (instancetype)allocWithZone:(struct _NSZone *)zone (+(instancetype)alloc 和 +(instancetype)new 都會走 allocWithZone ,多以直接重寫 allocWithZone 就ok了)
- (instancetype)copy
- (instancetype)mutableCopy
完整代碼:
+ (instancetype)sharedInstance {static MyPerson *person = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ person = [[super allocWithZone:nil] init]; });
return person; } + (instancetype)allocWithZone:(struct _NSZone *)zone {
return [MyPerson sharedInstance]; } - (instancetype)copy {
return [MyPerson sharedInstance]; } - (instancetype)mutableCopy {
return [MyPerson sharedInstance]; }
方法 2:
聲明:+ (instancetype)sharedInstance 單例方法
然後讓其他可能創建該對象的方法不可用,這裏使用到 __attribute__ 。這樣在調用下列方法時,編譯會報錯。
完整代碼:
+ (instancetype)sharedInstance; + (instancetype) alloc __attribute__((unavailable("use sharedInstance"))); + (instancetype) new __attribute__((unavailable("use sharedInstance"))); - (instancetype) copy __attribute__((unavailable("use sharedInstance"))); - (instancetype) mutableCopy __attribute__((unavailable("use sharedInstance")));
創建單例的正確姿勢