Kotlin Multiplatform 在 iOS 上使用 NSUserDefaults setValue String 时出错

Kotlin Multiplatform use NSUserDefaults setValue String on iOS got error

我写函数

    actual fun setItem(key: String, value: String) {
        NSUserDefaults.standardUserDefaults.setValue(value, key)
    }

并收到此错误。我认为值字符串并与 Any

一起使用
Showing Recent Messages
The following Kotlin source sets were configured but not added to any Kotlin compilation:

 * androidAndroidTestRelease

 * androidTestFixtures

 * androidTestFixturesDebug

 * androidTestFixturesRelease

You can add a source set to a target's compilation by connecting it with the compilation's default source set using 'dependsOn'.

See https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html#connecting-source-sets



> Task :shared:compileKotlinIosX64 FAILED

e: /Users/anh.nguyen25/Desktop/momo-app-vix/shared/src/iosMain/kotlin/vn/momo/core/modules/storage/FastStorage.kt: (14, 45): Overload resolution ambiguity: 

public external fun NSObject.setValue(value: Any?, forKey: String): Unit defined in platform.Foundation

public external fun NSObject.setValue(value: Any?, forKeyPath: String): Unit defined in platform.Foundation

public external fun NSObject.setValue(value: Any?, forUndefinedKey: String): Unit defined in platform.Foundation



FAILURE: Build failed with an exception.



* What went wrong:

Execution failed for task ':shared:compileKotlinIosX64'.

> Compilation finished with errors

setValue是KVO方法,与用户默认值无关。

替换为setObject:

NSUserDefaults.standardUserDefaults.setObject(value, key)

p.s。如果您需要使用 setValue 或者您将面临与其他方法相同的问题,您可以通过提供第二个参数名称来指定所需的方法,例如setValue(value, forKeyPath = key)

除了上述答案之外,如果您正在寻找 plug-and- play KMP key-value 商店,Multiplatform Settings 值得一试。它还在后台使用 NSUserDefaults