【问题标题】:Most Efficient way to Store Data in Swift在 Swift 中存储数据的最有效方法
【发布时间】:2017-08-06 19:38:00
【问题描述】:

我目前正在处理一个 Swift 项目,我想通过以下方式保存永久用户数据:

用户名 - 字符串列表(字符串数组)

这样当我搜索用户名时,我要么得到一个 nil 返回(如果用户名不存在),要么得到一个可以迭代的字符串列表。我知道一些保存用户数据的方法,但是,由于我是 Swift 新手,我不知道永久保存用户数据的所有方法。我也不知道哪些最适合我的需要。

【问题讨论】:

  • 任何特定方法的效率至少部分取决于音量。我们在这里谈论多少个用户名?每个将关联多少数据?
  • @BobWakefield 大概有 1-5 个用户名,字符串数组上有 8-35 个字符串
  • iOS 还是 macOS?无论哪种方式,都有常用的选项 - SQLite、Core Data、plist 文件或其他二进制文件。
  • @rmaddy 它在 iOS 中。我可以在其中存储数据对吗?就像与字符串数组关联的字符串。
  • @AshleyMills 这是 plist 的来源。

标签: ios swift swift3 local-storage


【解决方案1】:

这样的……

let people: [String: [String]] = ["Jim": ["bread", "fruit", "meat"],
              "Alan": ["pears", "peas", "turnip"],
              "Sue": ["cabbage", "rice", "bblueberries"]]

let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last!
let fileUrl = documentsUrl.appendingPathComponent("myfile")

(people as NSDictionary).write(to: fileUrl, atomically: true)

然后……

let people = NSDictionary(contentsOf: fileUrl) as! [String: [String]]

对于系统网址…https://developer.apple.com/reference/foundation/filemanager/1407726-urls

NSDictionary... https://developer.apple.com/reference/foundation/nsdictionary?language=swift

【讨论】:

  • 这是永久保存的吗?什么是 URL 的示例?你如何遍历 NSDictionary?我可以自动将数据对设置/接收到函数中吗?前任。 setValues(username, stringarray) 和 getArray(username)。
  • 是的,这是永久保存的。在答案中添加了一些 URL 详细信息,您将不得不亲自尝试其中的一些内容。编写一些代码,而不是在遇到问题时提出更多问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
相关资源
最近更新 更多