您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

Objective-C 單例模式實作與 Singleton 巨集封裝

編輯:iOS 技巧大全

單例是 iOS 開發裡最常被使用的設計模式之一,從 NSNotificationCenter 到 NSUserDefaults,幾乎到處都是。本文從原理出發,示範如何保證「永遠只有一個物件」,最後再把它抽成可重複使用的巨集。

什麼是單例

簡單說:同一個類別,无论你呼叫多少次,拿到的永遠是同一個物件,也就是只能被實例化一次。

實作的核心思路

物件的誕生必然經過 alloc(內部會呼叫 allocWithZone:)。因此只要攔住這一步,確保它只執行一次、並且是執行緒安全的,再把物件放在靜態區域,之後不論是 alloc、copy 都直接回傳這個實例即可。

幾個實作要點

  • 靜態全域變數不需要自行釋放(MRC 環境亦然)
  • 執行緒安全可用 @synchronized 或 GCD 的 dispatch_once,後者效能更好、寫法更乾淨
  • 初始化方法也可以只跑一次,避免屬性被重複覆寫

完整實作

@implementation myManager

static id instance;

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    // 寫法一:互斥鎖
    // @synchronized (self) {
    //     if (instance == nil) { instance = [super allocWithZone:zone]; }
    // }
    // 寫法二:GCD,保證只執行一次(推薦)
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (instance == nil) { instance = [super allocWithZone:zone]; }
    });
    return instance;
}

+ (instancetype)sharedSoundTools {
    instance = [[self alloc] init];
    return instance;
}

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

#pragma mark - MRC 相關
- (oneway void)release { /* 什麼都不做 */ }
- (instancetype)retain { return instance; }
- (instancetype)autorelease { return instance; }
- (NSUInteger)retainCount { return ULONG_MAX; } // 避免被誤 release 到崩潰

- (instancetype)init {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        self = [super init];
        if (self) { self.age = 10; }
    });
    return self;
}
@end

把它抽成巨集

把下面的內容存成 singleton.h,使用時只要引入這個標頭檔即可。

用法:.h 中寫 singletonInterface(myManager);,.m 中寫 singletonImplementation(myManager);。

#define singletonInterface(className) + (instancetype)shared##className;

#if __has_feature(objc_arc)
// ARC 版本
#define singletonImplementation(className) \
+ (instancetype)allocWithZone:(struct _NSZone *)zone { \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        if (instance == nil) { instance = [super allocWithZone:zone]; } \
    }); \
    return instance; \
} \
+ (instancetype)shared##className { \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); \
    return instance; \
} \
- (id)copyWithZone:(NSZone *)zone { return instance; }
#else
// MRC 版本
#define singletonImplementation(className) \
+ (instancetype)allocWithZone:(struct _NSZone *)zone { \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        if (instance == nil) { instance = [super allocWithZone:zone]; } \
    }); \
    return instance; \
} \
+ (instancetype)shared##className { \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); \
    return instance; \
} \
- (id)copyWithZone:(NSZone *)zone { return instance; } \
- (oneway void)release {} \
- (instancetype)retain { return instance; } \
- (instancetype)autorelease { return instance; } \
- (NSUInteger)retainCount { return ULONG_MAX; }
#endif
// 注意:巨集的最後一行「不要」留反斜線

另外提醒,巨集展開時會用到一個名為 instance 的靜態變數,記得在 .m 檔案的實作區塊頂端宣告 static id instance;。

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