gpt4 book ai didi

ios - 如何实现在 Swift 中获取初始化数据的 Singleton?

转载 作者:行者123 更新时间:2023-11-28 06:33:28 28 4
gpt4 key购买 nike

在此post ,很好地解释了如何在 Swift 中实现单例,基本上可以用两行来完成:

class TheOneAndOnlyKraken {
static let sharedInstance = TheOneAndOnlyKraken()
private init() {} //This prevents others from using the default '()' initializer for this class.
}

但是,如果我的 Singleton 应该用一些数据初始化,会发生什么?也许它需要封装一个 API key 或其他只能从外部 接收的数据。示例如下所示:

class TheOneAndOnlyKraken {
let secretKey: String
static let sharedInstance = TheOneAndOnlyKraken()
private init() {} //This prevents others from using the default '()' initializer for this class.
}

在那种情况下,我们不能将初始化程序设为私有(private),因为我们必须创建一个以 String 作为参数的初始化程序以满足编译器的要求:

init(secretKey: String) {
self.secretKey = secretKey
}

如何保存它并且我们仍然确保我们有一个单例的线程安全实例化?有没有办法我们可以避免使用 dispatch_once 或者我们必须默认回到我们使用 dispatch_once 的 Objective-C 方式来确保初始化程序确实只被调用一次?

最佳答案

首先,请注意您暗示的 ObjC 方式不是线程正确的。它可能是“安全的”,因为它不会崩溃并且不会产生未定义的行为,但它会默默地忽略具有不同配置的后续初始化。这不是预期的行为。已知在写入之后发生的读取器将不会接收到写入的数据。这不符合一致性。因此,抛开这种模式是正确的理论。

那么什么是正确的呢?正确的应该是这样的:

import Dispatch

class TheOneAndOnlyKraken {
static let sharedInstanceQueue: DispatchQueue = {
let queue = DispatchQueue(label: "kraken")
queue.suspend()
return queue
}()

private static var _sharedInstance: TheOneAndOnlyKraken! = nil
static var sharedInstance: TheOneAndOnlyKraken {
var result: TheOneAndOnlyKraken!
sharedInstanceQueue.sync {
result = _sharedInstance
}
return result
}

// until this is called, all readers will block
static func initialize(withSecret secretKey: String) {
// It is a programming error to call this twice. If you want to be able to change
// it, you'll need another queue at least.
precondition(_sharedInstance == nil)
_sharedInstance = TheOneAndOnlyKraken(secretKey: secretKey)
sharedInstanceQueue.resume()
}

private var secretKey: String
private init(secretKey: String) {
self.secretKey = secretKey
}
}

这需要对 TheOneAndOnlyKraken.intialize(withSecret:) 进行一次显式调用。在有人发出该调用之前,所有对 sharedInstance 的请求都将被阻止。第二次调用 initialize 会崩溃。

关于ios - 如何实现在 Swift 中获取初始化数据的 Singleton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39650409/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com