有时候是不是因为频繁地创建一个单例对象而头疼,一种方式要写好多遍?当然你可以用OC语言进行封装。但下面将介绍一种由C语言进行的封装。只要实现下面的方法,以后建单例对象只要二句话。
1.新建一个.h文件,在文件中实现以下方法:
1 / .h 2 #define singleton_interface(class) + (instancetype)shared##class; 3 4 // .m 5 #define singleton_implementation(class) \ 6 static class *_instance; \ 7 \ 8 + (id)allocWithZone:(struct _NSZone *)zone \ 9 { \ 10 static dispatch_once_t onceToken; \ 11 dispatch_once(&onceToken, ^{ \ 12 _instance = [super allocWithZone:zone]; \ 13 }); \ 14 \ 15 return _instance; \ 16 } \ 17 \ 18 + (instancetype)shared##class \ 19 { \ 20 if (_instance == nil) { \ 21 _instance = [[class alloc] init]; \ 22 } \ 23 \ 24 return _instance; \ 25 }
2.如何使用。
在想创建单例的类中的.h文件中写下第一句话:
singleton_interface(类名)
在.m文件中写下第二句话:
singleton_implementation(类名)
好了,以后在任何项目中导入这个头文件后,然后在类中实现这两句话,就可以轻松地使用单例了,再也不用频繁地重复写大量的代码了。看起来是不是很高大上!