您的位置:首页 > 移动开发 > Objective-C

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

2012-12-07 02:19 218 查看
之前写过一篇关于非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 就可以获取实例。
相关代码工程地址http://download.csdn.net/detail/kindazrael/4885433
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: