如何存储字典[String:[Object]]?

时间:2018-04-27 21:38:46

标签: ios swift nscoding

所以我有一个名为Restaurant的课程和一个[String:[Restaurant]]字典。如何正确存储此词典,以便在用户重新启动应用程序后,其中的数据不会丢失?

class Restaurant {
    var name: String?
    init?(name: String) {
        guard !name.isEmpty else {
            return nil
        }
        self.name = name
    }
}
var restaurants = [String: [Restaurant]]()
override func viewDidLoad() {
    super.viewDidLoad()
    // ...
    restaurants["Pizza"] = ...
}

1 个答案:

答案 0 :(得分:-1)

尝试使用realm.io

如果要同时使用decodable和realm对象来创建磁盘中的对象,可以按照以下步骤进行操作

import RealmSwift

class Restaurant: Object, Decodable {
  @objc dynamic var name: String?

  private enum CodingKeys: String, CodingKey { case name}

  convenience init( name: String?){
      self.init()
      self.name = name
  }

  convenience required init(from decoder: Decoder) throws {
      self.init()
      let container = try decoder.container(keyedBy: CodingKeys.self)
      self.name = try container.decode(String.self, forKey: .name)
  }
}

func saveToDisk(){
  let realm = try! Realm()
  try! realm.write {
      realm.add(restaurant)
  }
}

您可以调整它以保存餐厅对象数组

您可以使用其他不同的方法:

  CoreData

  Using a file 

  UserDefaults(too slow and not for large amount of data)