iOS大神班筆記02-模仿蘋果建立單例

來源:互聯網
上載者:User

標籤:大神   func   類比   告訴   建立   isp   異常類   重寫   name   

首先我們得要知道蘋果是如何?單例的:1.不能外界調用alloc,一調用就崩掉,其實就是拋異常(類內部第一次調用alloc就不崩潰,其他都崩潰)。

                   2.提供一個方法給外界擷取單例。

                       3.內部建立一次單例,什麼時候建立,程式啟動的時候建立單例。

然後我們來建立一個Person類。

Person.h#import <Foundation/Foundation.h>@interface Person : NSObject// 擷取單例+ (instancetype)sharePerson;@end
Person.m#import "Person.h"@implementation Person// 程式啟動時候建立對象// 靜態變數static Person *_instance = nil;// 作用:載入類// 什麼調用:每次程式一啟動,就會把所有的類載入進記憶體+ (void)load{    NSLog(@"%s",__func__);       _instance = [[self alloc] init];    }+ (instancetype)sharePerson{    return _instance;}+ (instancetype)alloc{        if (_instance) {        // 標示已經分配好了,就不允許外界在分配記憶體                // 拋異常,告訴外界不運用分配        // ‘NSInternalInconsistencyException‘, reason: ‘There can only be one UIApplication instance.‘        // 建立異常類        // name:異常的名稱        // reson:異常的原因        // userInfo:異常的資訊        NSException *excp = [NSException exceptionWithName:@"NSInternalInconsistencyException" reason:@"There can only be one Person instance." userInfo:nil];                // 拋異常        [excp raise];            }        // super -> NSObject 才知道怎麼分配記憶體    // 調用系統預設的做法, 當重寫一個方法的時候,如果不想要覆蓋原來的實現,就調用super    return [super alloc];}

  在這裡我只是想類比下蘋果底層是如何?單例的,我們一般情況下並不會使用這種方法。我們一般會使用如下方法:

+(instancetype)sharedPerson{    // 靜態變數    static Person *_instance = nil;        static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _instance = [[self alloc]init];    });    return _instance;}

 

iOS大神班筆記02-模仿蘋果建立單例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.