// .h文件
#define SingletonH + (instancetype)sharedInstance;
// .m文件
#define SingletonM \
static id _instance; \
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
\
+ (instancetype)sharedInstance \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instance; \
}
在需要实现单例的类的.h和.m文件下分别写下这两个宏的实现,会自动实现shareInstance方法,返回该类的单例对象,省去了工程下的代码量.
网友评论