iOS單例模式

#import <Foundation/Foundation.h>

@interface Instance : NSObject

+ (instancetype)sharedInstance;

@end
@implementation Instance

static Instance *instance;

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (id)copyWithZone:(NSZone *)zone
{
    return instance;
}
@end
@implementation Instance

static Instance *instance;

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    @synchronized(self) {
        if (instance == nil) {
            instance = [super allocWithZone:zone];
        }
    }
    return instance;
}

+ (instancetype)sharedInstance
{
    @synchronized(self) {
        if (instance == nil) {
            instance = [[self alloc] init];
        }
    }
    return instance;
}

- (id)copyWithZone:(NSZone *)zone
{
    return instance;
}
@end

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

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

  • 一、介紹 iOS單例模式(Singleton)單例模式的意思就是只有一個實例。單例模式確保某一個類只有一個實例,而...
    風(fēng)輕魚蛋閱讀 1,301評論 0 15
  • 網(wǎng)絡(luò)信息 @@@@@@@@@@@eg:事件處理中心@@@@@@@@@
    天涯笑笑生閱讀 256評論 0 0
  • (1)單例模式 在程序運行過程,一個類只有一個實例 (2)使用場合 在整個應(yīng)用程序中,共享一份資源(這份資源只需要...
    奧斯卡先生閱讀 367評論 1 0
  • 1.單例模式單例模式是一種常用的設(shè)計模式,對于一個單例類,必須保證任意時刻只有一個單例對象,并且自行實例化該對象,...
    亦晴工作室閱讀 530評論 0 0
  • IOS單例模式(Singleton)單例模式的意思就是只有一個實例。單例模式確保某一個類只有一個實例,而且自行實例...
    Living_元寶兒閱讀 1,369評論 1 6

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