如何避免通過[[alloc] init]創建iOS單例類?
網站普遍的創建單例類的方法有下面兩種:
+ (instancetype)sharedManager { static id _sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _sharedInstance = [[self alloc] init]; }); return _sharedInstance; }
+ (instancetype)sharedManager { static id _sharedInstance = nil; @synchronized(self) { if (_sharedInstance == nil) _sharedInstance = [[self alloc] init]; } return _sharedInstan<愛尬聊_百科大全>ce; }
但是該如何避免意外的用[[alloc] init]
創建呢?主要是發現網上找到的大多僅僅只有上面的代碼,少有考慮被init
或者copy
的情況
花霸王 6小時前
這樣寫就可以了
天若有情Simon 6小時前
額外創建有很多,還有new方法也可以,把這些方面都重載一遍返回 sharedManager 實例,或者直接拋出異常
2016幸運星 6小時前
又去stackovweflow找了下方法,我覺得既然是單例模式,調用者就應該嚴格按照單例的要求,通過統一的接口(這里是sharedInstance)去創建單例,而不應該出現調用[[class alloc] init]也能成功創建單例的情況,如果出現[[class alloc] init]的情況,我覺得更應該讓Xcode給出警告不能用此方法
xwxwbetter 6小時前
覆蓋allocWithZone和copyWithZone方法。因為通過alloc或者copy還是new,都是通過調用allocWithzone和copyWithzone來分配空間的。你可以把sharedManager 方法里面的代碼寫到這兩個方法里面,就可以從根本實現了單例的情況
soma218 6小時前
(instancetype)init {@throw [NSException exceptionWithName:@"Disable" reason:@"Please use init instead..." userInfo:nil];return self;}
Along.天神 6小時前
http://www.jianshu.com/p/08b1... 看看這篇我的寫博客.