iOS 再談單例的幾種寫法

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,041評論 0 9
  • 一個人的時光,是自己最安靜的時刻。安靜時的自己,可以幻想好多好多種的未來,可以把最美的夢裝點在這個只屬于自己的夜晚...
    夜落y閱讀 576評論 0 0
  • 由于紀云溪白天還要上班,所以在開業(yè)之前她就考慮要招一個人??墒沁@太不容易,她開不起太高的薪水,年輕人就覺得不劃算,...
    見手青閱讀 285評論 0 0
  • 我時不時給周圍的人講,我其實很內(nèi)向的。然后,不管我說話的語氣正經(jīng)不正經(jīng),周圍人總是略帶鄙夷和嘲諷的反問:你?能滔滔...
    壹言肆韻閱讀 606評論 3 1

友情鏈接更多精彩內(nèi)容