序言
單例的使用在我們開發(fā)iOS程序的時候的使用率是非常高的,在我們寫一個單例的時候,可能不止會用到一個單例,然而重復的代碼,我們要不止一次的粘貼,復制,還占用空間。這里給大家分享一下單例的宏定義的方法,廢話少說,開始!
代碼
下面是代碼:大家可以直接粘貼+復制(新建一個.h文件 把下面的代碼 粘進去就OK了)
// .h
#define singleton_interface(class) + (instancetype)shared##class;
// .m
#define singleton_implementation(class) \
static class *_instance; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
\
return _instance; \
} \
\
+ (instancetype)shared##class \
{ \
if (_instance == nil) { \
_instance = [[class alloc] init]; \
} \
\
return _instance; \
}
單例創(chuàng)建及使用
1.建一個.h文件

2.宏定義代碼

3.創(chuàng)建一個單例


4.單例的使用
