Objective C ARC下的单例模版宏 ARC Singleton template
2012-12-07 02:19
281 查看
之前写过一篇关于非ARC的单例模版宏的文章地址
但现在ARC的使用越来越广泛,原来的模版宏可能已经不是很适应,那介绍一下ARC版的模版宏的写法和用法
#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接收一个在应用生命周期只会被调用一次的代码块,而且它还是线程安全的
#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
但现在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
相关文章推荐
- Objective-C在ARC下结合GCD的单例模式和宏模版
- Objective-C在ARC下结合GCD的单例模式和宏模版
- objective-c中的Singleton单例模式的完整实现示例
- 【设计模式 - 23】之模版方法模式(Template)
- MGTemplateEngine 模版引擎简单使用以及MGTemplateEngine导入xcode6.1报错修改
- does not support Objective-C Automatic Reference Counting (ARC)
- Objective-C在ARC下结合GCD的单例模式和宏模版
- 黑马程序员——Objective--C笔记之ARC 和 autorelease
- template学习之零值初始化及字符串常量作(function template argument)函数模版参数问题
- BASH 文本模版的简单实现 micro_template_compile
- 模版方法模式/Template Method
- ARC forbids Objective-C objects in struct
- Asp.Net中DataGrid的模版列(TemplateColumn)内容控制简单方法。
- Django——模版Template报错
- objective-c启用ARC时的内存管理
- Objective-C内存管理第六弹:ARC
- [学习记录]怎么关闭Objective-C的ARC
- WPF Template模版之DataTemplate与ControlTemplate【一】
- Objective-C在ARC下结合GCD的单例模式和宏模版