gpt4 book ai didi

swift - 使用 NSKeyedArchiver 将对象传递给 WatchKit

转载 作者:行者123 更新时间:2023-11-30 12:56:49 25 4
gpt4 key购买 nike

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 方法,它们正在工作,但我仍然遇到运行时崩溃:[NSKeyedUnarchiverdecodeObjectForKey:]:无法解码 key (NS.objects)的类(Child)对象

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

最佳答案

好吧,我找到了解决方案,如果您具有相同的结构,则只需简单地设置类名即可

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

当您取消存档时也是如此:

NSKeyedUnarchiver.setClass(Parent.self, forClassName: "Parent")
NSKeyedUnarchiver.setClass(Child.self, forClassName: "Child")

关于swift - 使用 NSKeyedArchiver 将对象传递给 WatchKit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40320472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com