ios - 在 Objective-C 中使用 init 方法创建单例的安全方法

标签 ios objective-c nsobject

下一步我想采用使用共享实例的 GCD 方法,因此我创建了以下代码:

@implementation MyClass

static id sharedInstance;

#pragma mark Initialization

+ (instancetype)sharedInstance {
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    if (sharedInstance) {
        return sharedInstance;
    }
    @synchronized(self) {
        self = [super init];
        if (self) {
            sharedInstance = self;
        }
        return self;
    }
}

@end

我假设 sharedInstance 方法似乎没问题,但我不确定 init 方法。创建它的原因是我不希望人们使用我的 SDK,使用 init 方法,如果他们这样做......让它成为防弹的。

最佳答案

我建议完全不允许调用 init,而不是透明地将对 init 的调用重定向到单例实现,这可能会给您的 SDK 用户带来非常困惑的行为:

+ (instancetype)sharedInstance {
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] initPrivate];
    });
    return sharedInstance;
}

- (instancetype)init {
    @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"..." userInfo:nil];
}

- (instancetype)initPrivate {
    if (self = [super init]) {
        ...
    }
    return self;
}

关于ios - 在 Objective-C 中使用 init 方法创建单例的安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29748175/

相关文章:

swift - 如何从 NSObject 访问 SwiftUI 环境对象?

objective-c - NSObject +load 和 +initialize - 他们做什么?

ios - 覆盖准备方法的 Swift 发送器

ios - 第二个动画 block 中不遵守动画选项/错误

ios - 将 subview 添加到自定义类

ios - 如何在 UITableViewCell 中实现带圆角的投影?

ios - 连续淡入淡出动画

ios - 使用 Swift 的 Firebase 推送通知在 ios 11.4 中不起作用

ios - 什么是便利构造函数。我需要保留便利构造函数返回的对象吗

swift - 需要澄清 Swift 中的 AnyObject