-->

WatchKit NSUserDefaults and NSKeyedUnarchiver issu

2019-02-20 05:03发布

问题:

In my project I have a custom object called Country, which implements NSCoding

The code is shared across iphone and watch app by reference. Both app are in the same app group.

In my iPhone app I'm using NSUserDefaults to story a Country object, from watch app I'm reading the same object with following code:

var defaults = NSUserDefaults(suiteName: "group.my.group")
if let data = defaults?.objectForKey("country") as? NSData {
    if let country = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Country {
        println("done")
    }
}

This code in iPhone app works perfectly and the country variable is correctly created, in the Watch app it is throwing an error:

Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (Country)'

回答1:

Had the same problem, this helped me: https://devforums.apple.com/message/1093079#1093079