Search code examples
nskeyedarchiverwatchkit

Watchkit sharing data with iPhone app, NSInvalidUnarchiveOperationException


From my iPhone app I'm sending data to my Watch app through:

func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!) {
  if let data = NSKeyedArchiver.archivedDataWithRootObject(Country()) {
    reply(["data": data])
  }
}

In my Watch app I'm trying to read the data:

WKInterfaceController.openParentApplication(input, reply: { (replyValues, error) -> Void in
  if error == nil {
    if let data = replyValues["data"] as? NSData {
      if let temp = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Country {
        println("done")
      }
    }
  }
})

The following error is thrown:

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

Solution

  • NSKeyedArchiver/NSKeyedUnarchiver is only available to classes that are NSCoding compliant.

    Without further inspection, it seems your 'Country' class doesn't conform to the NSCoding protocol.

    Instead of confusing you with a long winded explanation, NSHipster has a fantastic page which explains how to implement NSCoding and make your objects archive friendly.

    I highly recommend it.

    http://nshipster.com/nscoding/