Objective C ARC下的單例模版宏 ARC Singleton template

之前寫過一篇關於非ARC的單例模版宏的文章地址

但現在ARC的使用越來越廣泛,原來的模版宏可能已經不是很適應,那介紹一下ARC版的模版宏的寫法和用法

寫法

ARCSingletonTemplate.h

#define SYNTHESIZE_SINGLETON_FOR_HEADER(className) \

\

+ (className *)shared##className;


#define SYNTHESIZE_SINGLETON_FOR_CLASS(className) \

\

+ (className *)shared##className { \

    static className *shared##className = nil; \

    static dispatch_once_t onceToken; \

    dispatch_once(&onceToken, ^{ \

        shared##className = [[self alloc] init]; \

    }); \

    return shared##className; \

}


基本是使用了 GCD中的dispatch_once接收一個在應用生命週期只會被調用一次的代碼塊,而且它還是線程安全的

用法

AppPreference.h

#import <Foundation/Foundation.h>

#import "ARCSingletonTemplate.h"

@interface AppPreference :NSObject

//使用宏模版生成單例所需要的code

SYNTHESIZE_SINGLETON_FOR_HEADER(AppPreference)

@end


AppPreference.m

#import "AppPreference.h"

@implementation AppPreference

//使用宏模版生成單例所需要的code

SYNTHESIZE_SINGLETON_FOR_CLASS(AppPreference)

//例子

- (void)sample{

   AppPreference* appPreference = [AppPreferencesharedAppPreference];

}

@end


使用 shareClassName 就可以獲取實例。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章