iOS 常用单例宏

在你的宏文件里面加入单例宏,快捷创建单例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#define SINGLETON_INTERFACE(className) + (instancetype)shared##className;

#define SINGLETON_IMPLEMENTATION(className) \
static id instance; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
instance = [super allocWithZone:zone]; \
}); \
return instance; \
} \
\
+ (instancetype)shared##className { \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
instance = [[self alloc] init]; \
}); \
return instance; \
} \
\
- (id)copyWithZone:(NSZone *)zone { \
return instance; \
}

调用

.h

1
SINGLETON_INTERFACE(Service)

.m

1
SINGLETON_IMPLEMENTATION(Service)

iOS 常用单例宏
http://example.com/2016/06/29/iOS-常用单例宏/
作者
guanzhendong
发布于
2016年6月29日
许可协议