OC中创建唯一单例的保险做法

这篇博客探讨了如何在Objective-C中确保单例的唯一性,通过全局变量、allocWithZone方法重写以及copy/mutableCopy方法的实现,确保了单例对象在不同路径下的创建始终返回同一实例。博客还提供了示例代码并展示了运行结果,验证了单例的正确性。
摘要由CSDN通过智能技术生成

很久之前的一次面试中被问到如何确保单例的唯一性,我记得之前想到的是用宏来保证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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星仔20180409

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值