ios - Kotlin / native : Can someone help me in suggesting how to create a frozen singleton that takes in init parameters?

标签 ios kotlin kotlin-multiplatform kotlin-native

下面的代码将不起作用,因为一旦我们尝试像 SomeClass.getInstance() 或它的任何其他属性一样访问它,就会创建伴随对象并使其不可变,我不会能够初始化 someClass 属性。我希望它是不可变的/卡住的(因为这将从多个线程访问)但是当它需要参数时我不能这样做。

有什么建议吗?

actual open class SomeClass private constructor(private val someProperty: SomeProperty) {
    actual companion object {
        private var someClass: SomeClass? = null
        fun initialize(someProperty: SomeProperty){
            someClass = SomeClass(someProperty)
        }
        actual fun getInstance(): SomeClass {
            if (someClass == null) {
                throw UninitializedPropertyAccessException("SomeClass is not initialised yet")
            }
            return someClass as SomeClass
        }
    }
}

一种可能的解决方案是在此处使用 AtomicReference。像这样:

actual open class SomeClass private constructor(private val someProperty: SomeProperty) {
    actual companion object {
        private var someClassAtomicRef: AtomicReference<SomeClass?> = AtomicReference(null)
        fun initialize(someProperty: SomeProperty){
            val someClass = SomeClass(someProperty)
            someClassAtomicRef.value = someClass.freeze()
        }
        actual fun getInstance(): SomeClass {
            return someClassAtomicRef.value ?: throw UninitializedPropertyAccessException("SomeClass is not initialised yet")
        }
    }
}

上面代码的问题是我可以再次调用 SomeClass.initialise 并在 AtomicReference 中有另一个 SomeClass 实例。

有没有更好的方法来实现这一目标?

最佳答案

Atomic Reference 是通往这里的路

actual open class SomeClass private constructor(private val someProperty: SomeProperty) {
    actual companion object {
        private var someClassAtomicRef: AtomicReference<SomeClass?> = AtomicReference(null)
        fun initialize(someProperty: SomeProperty){
            val someClass = SomeClass(someProperty)
            someClassAtomicRef.compareAndSet(null, someClass.freeze())
        }
        actual fun getInstance(): SomeClass {
            return someClassAtomicRef.value ?: throw UninitializedPropertyAccessException("SomeClass is not initialised yet")
        }
    }
}

关于ios - Kotlin / native : Can someone help me in suggesting how to create a frozen singleton that takes in init parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59484818/

相关文章:

java - 即使未在构建方法中声明变量,setState 也不会更新 UI

android - 如何使 Anko 中的 indeterminateProgressDialog 不可取消?

gradle - 将 kapt 与多平台子项目一起使用

swift - 未捕获的 Kotlin 异常 : kotlin. native.IncorrectDereferenceException:非法尝试访问非共享

ios - Swift Firebase 注销问题,只有在重新打开应用程序后才能成功注销

ios - 在 iOS 应用程序中存储包含的 AWS 凭证的最佳位置

iphone - 找不到 Cocos2D CGRectIntersect?

android - TextInputEditText - CompoundDrawable 未居中

ios - 无法将 kotlin 接口(interface)的快速实现传递给 kotlin native

iphone - 远程清除 iOS 应用程序