很久之前的一次面试中被问到如何确保单例的唯一性,我记得之前想到的是用宏来保证alloc方法不会被调用
+(instancetype)alloc NS_UNAVAILABLE;
之后面试官说道能不能从内存分配的角度来确保单例唯一性,因为还不太了解OC类的内存创建方法就没有回答上来。后来突然想起这个问题遂记录一下以下这种方式创造单例。
// XZNotification.h
@interface XZNotification : NSObject<NSCopying, NSMutableCopying>
/**
* @brief 创建一个通知中心单例,请不要自己通过alloc和init创建,而是调用此方法
* @return 唯一通知中心实例变量
*/
+ (XZNotification *)notification;
@end
// XZNotification.m
@implementation XZNotification
// 创建一个全局变量
static XZNotification* instance = nil;
+ (XZNotification *)notification {
return [[XZNotification alloc] init];
}
// 该方法是防止外部即便不小心使用了alloc的方式使用了本类创建实例,仍旧可以返回唯一的实例给到外部
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone:zone];
});
return instance;
}
// 该方法保证即便是外部对该单例使用了copy方法,也是会仍旧返回唯一的实例给到外部
- (id)copyWithZone:(struct _NSZone *)zone {
return instance;
}
// 该方法保证即便是外部对该单例使用了mutableCopy方法,也是会仍旧返回唯一的实例给到外部
- (id)mutableCopyWithZone:(NSZone *)zone {
return instance;
}
@end
int main(int argc, char* argv[]) {
@autoreleasepool {
XZNotification *notification = [XZNotification notification];
NSLog(@"notification: %@", notification);
XZNotification *notification2 = [[XZNotification alloc] init];
NSLog(@"notification2: %@", notification2);
XZNotification *notification3 = [notification copy];
NSLog(@"notification3: %@", notification3);
XZNotification *notification4 = [notification mutableCopy];
NSLog(@"notification4: %@", notification4);
}
}
##运行结果
notification: <XZNotification: 0x600002fb8030>
notification2: <XZNotification: 0x600002fb8030>
notification3: <XZNotification: 0x600002fb8030>
notification4: <XZNotification: 0x600002fb8030>