无法解码类的对象 [英] Cannot decode object of class
问题描述
我正在尝试向Watchkit扩展发送类",但出现此错误.
I am trying to send a "Class" to my Watchkit extension but I get this error.
*由于未捕获的异常'NSInvalidUnarchiveOperationException'而终止应用程序,原因:'* -[NSKeyedUnarchiver encodeObjectForKey:]:无法解码类(MyApp.Person)的对象
* Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '* -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (MyApp.Person)
在iOS App上进行存档和取消存档工作正常,但在与watchkit扩展进行通信时却无法正常工作.怎么了?
Archiving and unarchiving works fine on the iOS App but not while communicating with the watchkit extension. What's wrong?
InterfaceController.swift
InterfaceController.swift
let userInfo = ["method":"getData"]
WKInterfaceController.openParentApplication(userInfo,
reply: { (userInfo:[NSObject : AnyObject]!, error: NSError!) -> Void in
println(userInfo["data"]) // prints <62706c69 7374303...
if let data = userInfo["data"] as? NSData {
if let person = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Person {
println(person.name)
}
}
})
AppDelegate.swift
AppDelegate.swift
func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!,
reply: (([NSObject : AnyObject]!) -> Void)!) {
var bob = Person()
bob.name = "Bob"
bob.age = 25
reply(["data" : NSKeyedArchiver.archivedDataWithRootObject(bob)])
return
}
Person.swift
Person.swift
class Person : NSObject, NSCoding {
var name: String!
var age: Int!
// MARK: NSCoding
required convenience init(coder decoder: NSCoder) {
self.init()
self.name = decoder.decodeObjectForKey("name") as! String?
self.age = decoder.decodeIntegerForKey("age")
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.name, forKey: "name")
coder.encodeInt(Int32(self.age), forKey: "age")
}
}
推荐答案
注意:尽管此答案中的信息是正确的,但 way 更好的答案是以下一种通过@agy.
NOTE: While the information in this answer is correct, the way better answer is the one below by @agy.
这是由于编译器创建MyApp.Person
& MyAppWatchKitExtension.Person
来自同一班.通常是由于跨两个目标共享同一类,而不是创建一个框架来共享该类.
This is caused by the compiler creating MyApp.Person
& MyAppWatchKitExtension.Person
from the same class. It's usually caused by sharing the same class across two targets instead of creating a framework to share it.
两个修复程序:
正确的解决方法是将Person
提取到框架中.主应用程序和watchkit扩展应该使用该框架,并将使用相同的*.Person
类.
The proper fix is to extract Person
into a framework. Both the main app & watchkit extension should use the framework and will be using the same *.Person
class.
解决方法是在保存&交上来. NSDictionary
将是代码&可在应用程序和扩展程序中解码.做到这一点的一种好方法是改为在Person
上实现RawRepresentable
协议.
The workaround is to serialize your class into a Foundation object (like NSDictionary
) before you save & pass it. The NSDictionary
will be code & decodable across both the app and extension. A good way to do this is to implement the RawRepresentable
protocol on Person
instead.
这篇关于无法解码类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!