1
class Parent: NSObject, NSCoding {
    var name : String?
    var childs : [Child]?

    override init() {}

    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "name")
        aCoder.encode(childs, forKey: "childs")
    }

    required init(coder aDecoder: NSCoder) {
        name = aDecoder.decodeObject(forKey: "name") as? String
        childs = aDecoder.decodeObject(forKey: "childs") as? [Child]

        super.init()
    }
}

class Child: NSObject, NSCoding {
    var name: String?

    override init() {}

    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "name")
    }

    required init(coder aDecoder: NSCoder) {
        name = aDecoder.decodeObject(forKey: "name") as? String
        super.init()
    }
}

// iOS side:

public func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Swift.Void) {

    var parent = Parent()
    parent.name = "John"

    var child1 = Child()
    var child2 = Child()

    parent.childs = [child1, child2]

    NSKeyedArchiver.setClassName("Parent", for: Parent.self)

    let data = NSKeyedArchiver.archivedData(withRootObject: parent)
    replyHandler(["parent": data as AnyObject])

}

// watchOS side:

if WCSession.isSupported() {

    session = WCSession.default()
    session!.sendMessage(["getParent": "getParent"], replyHandler: { (response) -> Void in

        if let rawParent = response as? [String:Data] {

            NSKeyedUnarchiver.setClass(Parent.self, forClassName: "Parent")
            if let parent = NSKeyedUnarchiver.unarchiveObject(with: data) as? Parent {
                // do something
            }

        }
    }, errorHandler: { (error) -> Void in
        print(error)
    })
}

在这种情况下,如您所见,我使用了正在工作的 NSKeyedUnarchiver.setClass 和 NSKeyedArchiver.setClassName 方法,但我仍然遇到运行时崩溃:[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (Child) for key (NS.objects)

如果我删除NSKeyedUnarchiver.setClass(Parent.self, forClassName: "Parent")NSKeyedArchiver.setClassName("Parent", for: Parent.self)行,我会得到相同的错误,但对于 Parent 类。所以我确信我必须对 Child 使用相同的方法调用,但我不知道在哪里。有人有什么想法吗?

4

1 回答 1

1

好的,我找到了解决方案,如果您具有相同的结构,您只需将类名设置在彼此之后

NSKeyedArchiver.setClassName("Parent", for: Parent.self)
NSKeyedArchiver.setClassName("Child", for: Child.self)

取消归档时也是如此:

NSKeyedUnarchiver.setClass(Parent.self, forClassName: "Parent")
NSKeyedUnarchiver.setClass(Child.self, forClassName: "Child")
于 2016-10-29T15:19:05.490 回答