iOS單例詳解

單例:整個程序只建立一次,全局共用。安全

  1. 單例的建立
    // SharedPerson.h 文件中
    + (instancetype)share;
    // SharedPerson.m 文件中
    static SharedPerson *_person;
    + (instancetype)allocWithZone:(struct _NSZone *)zone{
        static dispatch_once_t predicate;
        dispatch_once(&predicate, ^{
            _person = [super allocWithZone:zone];
        });
        return _person;  
    }
    
    + (instancetype)share {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _person = [[self alloc]init];
        });
        return _person;
    }
    - (id)copyWithZone:(NSZone *)zone { return _person; }

     

  2. 分析單例
    • static SharedPerson *_person : 利用static關鍵字來確保建立的單例對象_person只能在此類中能夠訪問到;將_person定義成全局變量爲了確保其生命週期存在於整個程序中,期間不被銷燬.
    • dispatch_once : 此函數確保_person對象在程序中只會建立一次,而且也保證了建立時的線程安全。
    • + (instancetype)share : 提供便捷的類方法來建立單例對象,強烈建議用此法建立對象。
    • + (instancetype)allocWithZone:(struct _NSZone *)zone : [SharedPerson alloc]分配對象內存時,實際會調此函數allocWithZone:(struct _NSZone *)zone,因此須要重寫此方法來保證單例對象只會建立一次,並且是必須重寫此方法,防止其餘開發者直接用初始化方法來建立單例對象函數

    • - (id)copyWithZone:(NSZone *)zone : 此函數來保證單例對象能夠copy再獲得一個如出一轍的對象。spa

相關文章
相關標籤/搜索