单例的封装

在项目中,我们需要全局只有一个实例,节省不必要的内存,这时我们就需要使用单例生成对象。

这时把单例的代码封装成宏,就能方便我们下次使用了。

在.h .m里直接导入头文件,调用 传入类名即可!

 

singleton_interface(DataManager)

singleton_implementation(DataManager)

 1 // .h
 2 #define singleton_interface(className) + (instancetype)shared##className;
 3 
 4 // .m
 5 // 最后一句不要斜线
 6 #define singleton_implementation(className) \
 7 static className *_instace; \
 8 \
 9 + (id)allocWithZone:(struct _NSZone *)zone \
10 { \
11     static dispatch_once_t onceToken; \
12     dispatch_once(&onceToken, ^{ \
13         _instace = [super allocWithZone:zone]; \
14     }); \
15     \
16     return _instace; \
17 } \
18 \
19 + (instancetype)shared##className \
20 { \
21     if (_instace == nil) { \
22         _instace = [[className alloc] init]; \
23     } \
24     \
25     return _instace; \
26 }
单例

 

posted @ 2014-03-09 22:44  努力努力再努力吧  阅读(223)  评论(0编辑  收藏  举报