[SOLVED] Kotlin Multiplatform use NSUserDefaults setValue String on iOS got error

Issue

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

Solution

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)

Answered By – Pylyp Dukhov

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.