.h文件中
#define SKSingletonH(__className)\
+ (__className *)shareInstance;\
.m文件中
#define SKSingletonM(__className)\
\
static __className *_instance = nil;\
\
+ (__className *)shareInstance {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [[self alloc] init];\
});\
return _instance;\
}\
\
+ (instancetype)allocWithZone:(struct _NSZone *)zone {\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
_instance = [super allocWithZone:zone];\
});\
return _instance;\
}\
\
- (id)copy {\
return _instance;\
}\
\
- (id)mutableCopy {\
return _instance;\
}\
本文介绍了使用Objective-C实现单例模式的方法。通过宏定义在.h文件中声明单例,并在.m文件中利用dispatch_once确保线程安全地初始化实例。此外,还重写了allocWithZone和copy等方法来确保单例的正确性和一致性。
4693

被折叠的 条评论
为什么被折叠?



