【问题标题】:What happens if the init method of a singleton class is called before the +sharedInstance method..?如果在 +sharedInstance 方法之前调用单例类的 init 方法会发生什么......?
【发布时间】:2015-06-26 09:53:16
【问题描述】:

如果在 +sharedInstance 方法之前调用单例类的 init 方法会发生什么..?这会产生一个新对象吗?如果不是,那么如何返回相同的实例?在 sharedInstance 中声明静态变量这一事实会对整体结果产生任何影响..?

+ (LibraryAPI*)sharedInstance
{
    // 1
    static LibraryAPI *_sharedInstance = nil;

    // 2
    static dispatch_once_t oncePredicate;

    // 3
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[LibraryAPI alloc] init];
    });
    return _sharedInstance;
}

【问题讨论】:

  • 看看这个 SO question
  • 你的问题我不清楚。如果我调用 [[LibraryAPI alloc] init] 5 次,它将创建并返回 5 个对象。但是如果我调用 [LibraryAPI sharedInstance] 它总是会返回单例对象。

标签: ios objective-c iphone singleton


【解决方案1】:

在Objective-C 中,类的init 方法只是带有'init' 前缀的方法。这是 objc 和 swift 之间最大的区别之一。因此,如果您调用了不好的 init 方法,但当您的 init 方法成功返回时,您无疑会初始化一个新实例。

函数内的静态变量在调用之间保持其值。因此,每次调用方法 sharedInstance 时,它都会为您提供相同的实例。有关静态变量的更多信息,请查看here

【讨论】:

    【解决方案2】:

    这取决于 init 方法是如何实现的。默认情况下,您可以使用 init 创建一个新对象。为了防止创建此类的实例,您可以在 init 方法中返回 nil 并为您的类创建一个私有初始化程序。

    -(instancetype)init {
        return nil;
    }
    
    -(instancetype)localInit {
        if(!self) {
            self = [super init];
        }
        return self;
    }
    

    所以这条线

    _sharedInstance = [[LibraryAPI alloc] init];
    

    会变成

    _sharedInstance = [[LibraryAPI alloc] localInit];
    

    【讨论】:

    • 在这种情况下不会出现“_sharedInstance = [[LibraryAPI alloc] init];”行也收到 nil 作为回报..?
    • 你是对的!我将删除代码示例。基本上,您可以编写另一个 init 方法,该方法无法从您的班级外部访问 --> 我更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 2013-07-17
    • 2013-09-26
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多