1.為什么再談皿淋?
常規(guī)的單例寫法有兩種
+ (Student *)defaultInstance
{
static Student *defaultInstance = nil;
if (!defaultInstance)
{
defaultInstance = [[self alloc] init];
}
return defaultInstance;
}
或
+ (Student *)sharedManager
{
static Student *sharedInstance = nil;
static dispatch_once_t predicate;//此象必須是全局或者靜態(tài)對象才能保證唯一性
dispatch_once(&predicate, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
這兩種寫法的優(yōu)缺點都是老生常談惠勒,本文不再贅述。
這兩種寫法的最大問題其實是不能保證別人只通過這種方式獲取該對象靴跛。若直接使用Student *std = [Student alloc] init];
的方式去創(chuàng)建對象返咱,則獲取到的是一個新的對象购啄。
2.解決方案
模仿UIApplication
重寫init
方法巨柒。調(diào)用init
時拋出異常,禁止別人調(diào)用馍悟。
-
在.m文件中
static Student *student = nil;+ (void)load { student = [[self alloc] init]; } //此方法和load選一個寫即可畔濒,兩個方法的區(qū)別下篇文章講 //+ (void)initialize //{ // student = [[self alloc] init]; //} + (instancetype)shareInstance { return student; } - (instancetype)init { if (student) { //拋異常 NSException *exp = [NSException exceptionWithName:NSInternalInconsistencyException reason:@"There can only be one Student instance." userInfo:nil]; [exp raise]; } return [super init]; }
如這樣處理,在調(diào)用init
時會拋出異常锣咒。
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'There can only be one Student instance.'
.
.//省略無關(guān)內(nèi)容
.
libc++abi.dylib: terminating with uncaught exception of type NSException