创建线程安全的单例(ARC或 非ARC)
生活随笔
收集整理的這篇文章主要介紹了
创建线程安全的单例(ARC或 非ARC)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一:創(chuàng)建 宏 文件?SynthesizeSingleton.h
SynthesizeSingleton.h#if __has_feature(objc_arc) // ARC Version#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \ \ + (classname *)shared##classname\ {\static classname *shared##classname = nil;\static dispatch_once_t onceToken;\dispatch_once(&onceToken, ^{\shared##classname = [[classname alloc] init];\});\return shared##classname;\ }#else // Non-ARC Version#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \ static classname *shared##classname = nil; \ + (classname *)shared##classname \ { \@synchronized(self) \{ \if (shared##classname == nil) \{ \shared##classname = [[self alloc] init]; \} \} \return shared##classname; \ } \ \ + (id)allocWithZone:(NSZone *)zone \ { \ @synchronized(self) \ { \ if (shared##classname == nil) \ { \ shared##classname = [super allocWithZone:zone]; \ return shared##classname; \ } \ } \ return nil; \ } \ - (id)copyWithZone:(NSZone *)zone \ { \ return self; \ } \ - (id)retain \ { \ return self; \ } \ - (NSUInteger)retainCount \ { \ return NSUIntegerMax; \ } \ - (oneway void)release \ { \ } \ - (id)autorelease \ { \ return self; \ }#endif二:使用
MyClass.h@interface MyClass : NSObject+(DataStorage *)sharedMyClass;@end MyClass.m#import "SynthesizeSingleton.h" @implementation MyClass SYNTHESIZE_SINGLETON_FOR_CLASS(MyClass) @end參考資料
轉(zhuǎn)載于:https://www.cnblogs.com/cocoajin/p/3176265.html
總結(jié)
以上是生活随笔為你收集整理的创建线程安全的单例(ARC或 非ARC)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【WPF】提高InkAnalyer手写汉
- 下一篇: Vim 的补全模式加速器,轻松玩转全部