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

标签 swift

我面临使用 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/

相关文章:

ios - 为了 "reload"应用程序,注销功能应该是什么样的?

ios - 在 iOS Swift 项目中从 "2015-01-17T20:00Z"创建 NSDate

ios - NSURL 不会从字符串初始化为远程字体文件 (.TTF)

ios - 如何在 Realm Swift 中使用 NOT IN

ios - 无法修复错误 : unexpectedly found nil while unwrapping an Optional value

swift - 在 Swift 中,你能写一个扩展,它返回扩展所在类的类型化实例吗?

ios - 如何在 Swift 中将新项目添加到我的多类型数组

ios - 使用 tableview 设置 uisearchdisplaycontroller 时出现问题 - Swift

xcode - 登录后尝试在两个 View Controller 之间传递数据

ios - 如何使用 Dropbox API 重新连接应用程序