ios快速生成单例(宏)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//.h
# define single_interface(className) + (className *)shared##className;
//.m
// 代表下一行也属于宏
// ## 是分隔符
# define single_implementation(className)
static className *_instance;
+ (className *)shared##className
{
if (_instance == nil) {
_instance = [[self alloc] init];
}
return _instance;
}
+ (id)allocWithZone:(NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}

把它写到 单独的.h文件或 .pch文件中
如果 想把某个 类变成单例, 在.h中写single_interface(类名)在.m中写 single_implementation(类名)这个类就是单例了

原文链接: http://blog.csdn.net/zhz459880251/article/details/49885907