有時候是不是因為頻繁地創建一個單例對象而頭疼,一種方式要寫好多遍?當然你可以用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(類名)
好了,以后在任何項目中導入這個頭文件后,然后在類中實現這兩句話,就可以輕松地使用單例了,再也不用頻繁地重復寫大量的代碼了。看起來是不是很高大上!
