您的位置:首页 > 其它

ARC版的模版宏的写法和用法

2015-01-05 15:24 176 查看
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 就可以获取实例。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: