我遇到了使用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.
}
}
答案 0 :(得分:1)
那是因为您正在归档Person
对象而不是[String: AnyObject]
。
您可以归档Person
,并将其解压缩为Person
或归档[String: AnyObject]
并提取该Person
。你不能同时使用它们,因为它们是不同的类型。
如果您要归档NSCoding
对象,请确保在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...
}
之后,你可以做......
CDialogTemplate