您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 單例模式的設計要點與實作

編輯:iOS 相關資訊

單例模式確保某個類別在整個應用程式中只有一個實例,並由該類別自行建立與提供這個實例。常用於全域設定、快取、日誌或服務管理。

核心要點

  • 只能有一個實例。
  • 必須自行建立實例。
  • 必須向系統提供同一個實例。

Objective-C 實作

實作時通常會宣告靜態變數,透過共享方法檢查是否為 nil,並重寫 allocWithZone 避免重複配置。若使用手動記憶體管理,還需處理 copy、retain、release 與 autorelease。

static SurveyRunTimeData *sharedObj = nil;

+ (SurveyRunTimeData *)sharedInstance {
    @synchronized (self) {
        if (sharedObj == nil) {
            sharedObj = [[self alloc] init];
        }
    }
    return sharedObj;
}

+ (id)allocWithZone:(NSZone *)zone {
    @synchronized (self) {
        if (sharedObj == nil) {
            sharedObj = [super allocWithZone:zone];
            return sharedObj;
        }
    }
    return nil;
}

在 ARC 環境下,通常只需要 sharedInstance 與 dispatch_once 即可達到相同效果,程式碼更簡潔。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved