Search code examples
swiftsprite-kiticloud

iCloud keyValue crashing my game


Trying to retrieve an int from iCloud using keyValue pairs. Can someone explain to me why this is crashing with the error:

 '[<NSUbiquitousKeyValueStore 0x170287e40> valueForUndefinedKey:]: this class is not key value coding-compliant for the key current.'

It worked just fine in my previous projects.

 var iCloudKeyStore: NSUbiquitousKeyValueStore = NSUbiquitousKeyValueStore()

 func loadSavedData() {

    if let cloudCurrent = iCloudKeyStore.value(forKey: "current") as! Int? { /* <-------- Crashes on this line */
        print("Current Level Found From iCloud: \(cloudCurrent)")
        currentLevel = cloudCurrent
    }else{
        print("No Current Level Found")
    }

    if let cloudAchieved = iCloudKeyStore.value(forKey: "achieved") as! Int? {
        print("Current Level Found From iCloud: \(cloudAchieved)")
        levelAchieved = cloudAchieved
    }else{
        print("No Achieved Level Found")
    }

Solution

  • value(forKey:) is for accessing instance variables of an object dynamically. I. e. Key-Value-Coding.

    There is no instance variable named "current" on that object. You want to access values stored in the store, which, according to the docs should be done using object(forKey:).