【原】ios下比較完美的單例模式,已驗證

來源:互聯網
上載者:User

標籤:style   blog   io   color   ar   os   使用   sp   strong   

網上關於ios單例模式實現的文章已經很多了,有很多版本,裡面有對的也有不對的。我在使用過程中很難找到一個比較完美的方法,索性自己寫一個吧,經過項目驗證是比較合理的一個版本。

static PRAutoLoginView *s_sharedInstance = nil;+ (PRAutoLoginView *)shareInstance{    @synchronized(self)    {        if (s_sharedInstance == nil) {            s_sharedInstance = [[[self class] hideAlloc] init];        }    }    return s_sharedInstance;}#pragma mark --#pragma mark singleton apis+ (id)hideAlloc{    return [super alloc];}+ (id)alloc//徹底屏蔽掉alloc函數{    NSAssert(1 == 0, @"[PRAutoLoginView]please use +shareInstance instead of alloc!");    return nil;}+ (id)new{    return [self alloc];}+ (id)allocWithZone:(struct _NSZone *)zone{    @synchronized(self)    {        if (s_sharedInstance == nil) {            s_sharedInstance = [super allocWithZone:zone];            return s_sharedInstance;        }    }    return nil;}- (id)copyWithZone:(NSZone *)zone{    NSAssert(1 == 0, @"[PRAutoLoginView]copy is not permitted!");    [self retain];    return self;}- (id)mutableCopyWithZone:(NSZone *)zone{    return [self copyWithZone:zone];}

這裡要注意的一點時,allocWithZone時預設調用的,即使你沒有顯式地調用alloc或者allocWithZone,因此需要重載

【原】ios下比較完美的單例模式,已驗證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.