gpt4 book ai didi

swift - 使用 swift 使用 unarchiveObjectWithFile 取消归档字典

转载 作者:行者123 更新时间:2023-11-30 10:01:57 24 4
gpt4 key购买 nike

我面临使用 unarchiveObjectWithFile 获取的数据的问题。我寄了一本字典存档。我得到的数据在调试时显示了值,但我无法从数据中提取键的确切值。总是得到零值

这是我的代码

class Person : NSObject, NSCoding {
struct Keys {
static let Name = "name"
static let Age = "age"
}

var name: [String] = []
var age: [Int] = []

init(dictionary: [String : AnyObject]) {
name = dictionary[Keys.Name] as! [String]
age = dictionary[Keys.Age] as! [Int]
}

func encodeWithCoder(archiver: NSCoder) {
archiver.encodeObject(name, forKey: Keys.Name)
archiver.encodeObject(age, forKey: Keys.Age)
}

required init(coder unarchiver: NSCoder) {

if let namesList = unarchiver.decodeObjectForKey(Keys.Name) as? [String] {
name = namesList
print("name\(name)")
}
if let agesList = unarchiver.decodeObjectForKey(Keys.Age) as? [Int] {
age = agesList
print("age \(age)")
}
super.init()
}
}

// View controller
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

let persons: [String:AnyObject] = [
"name" : ["a","b","c"],
"age" : [2,3,4]
]

let personObj = Person(dictionary: persons)
NSKeyedArchiver.archiveRootObject(personObj, toFile: "/Users/shuvo/Desktop/Data.json")

let responseObject = NSKeyedUnarchiver.unarchiveObjectWithFile("/Users/shuvo/Desktop/Data.json") as? Person

if let unwrapData: AnyObject = responseObject {
let nameArr = unwrapData["name"] as? [String]
let ageArr = unwrapData["age"] as? [Int]
print("age \(ageArr) name \(nameArr)")
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

最佳答案

这是因为您正在归档 Person 对象,而不是 [String: AnyObject]

您可以存档 Person,然后将其提取为 Person,或者存档 [String: AnyObject] 并提取它。您不能同时使用两者,因为它们是不同的类型。

如果您想存档 Person 对象,请确保实现 NSCoding 协议(protocol),并在您的 Person 类中具有类似的内容...

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

required init?(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey: "name") as! [String]
self.age = aDecoder.decodeObject(forKey: "age") as! [Int]
}

之后,你就可以做...

if let responseObject = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? Person {
// You can use `responseObject` as a `Person` object here...
}

关于swift - 使用 swift 使用 unarchiveObjectWithFile 取消归档字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38021765/

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