Home > Blockchain >  Kotlin Multiplatform use NSUserDefaults setValue String on iOS got error
Kotlin Multiplatform use NSUserDefaults setValue String on iOS got error

Time:03-23

I write function

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

And got this error. I think value string and use with 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

CodePudding user response:

setValue is KVO method which has nothing to do with user defaults.

Replace it with setObject:

NSUserDefaults.standardUserDefaults.setObject(value, key)

p.s. if you need to use setValue or you'll face same problem with other methods, you can specify the needed method by providing the second parameter name, e.g. setValue(value, forKeyPath = key)

CodePudding user response:

In addition to the answer above, if you're looking for a plug-and- play KMP key-value store, Multiplatform Settings is worth checking out. It also uses NSUserDefaults under the hood.

  • Related