在Objective-C中使用init方法创建单例的安全方法 [英] Safe way to create singleton with init method in Objective-C

查看:115
本文介绍了在Objective-C中使用init方法创建单例的安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to take the GCD approach of using shared instances to the next step so I created the following code:

@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

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

I assume the sharedInstance method seems to be ok but I am unsure about the init method. The reason for creating this is that I don't want people using my SDK, to use the init method, and if they do ... make it bullet proof.

推荐答案

而不是透明地将对 init 的调用重定向到单例实现,这可能会导致SDK用户的行为非常混乱,我建议不要允许完全调用init:

Instead of transparently redirecting calls to init to the singleton implementation which can cause very confusing behaviour for the users of your SDK, I suggest not allowing to call init at all:

+ (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;
}

这篇关于在Objective-C中使用init方法创建单例的安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆