【问题标题】:Trouble on plist file using swift使用 swift 处理 plist 文件的问题
【发布时间】:2016-01-06 17:52:36
【问题描述】:

我有两个名为“Countries”和“Places”的变量,我正在尝试读取 Data.plist 并检索一些值

这是 Data.plist:

Data.plist

我无法从变量中读取 plist。

举个例子,Countrys 的值是“Italia”,Places 的值是“Naples”,我如何检索写在“Item 0”和“Item 1”中的两个不同的值。

我一直在互联网上寻找一些可以帮助我的教程,但我无法让其中任何一个适用于我的案例(我使用了更多教程示例,但由于我的声誉低,我不能发布超过 2 个链接)。

我尝试按照这些教程进行操作:

Swift - searching through dictionaries in an array in a plist

http://sweettutos.com/2015/06/03/swift-how-to-read-and-write-into-plist-files/

例如,我尝试在不使用“变量”的情况下使用此代码,但即使这样也不起作用:

let path = NSBundle.mainBundle().pathForResource("Dati", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
let value: AnyObject = (dict!.objectForKey("Italia")!.objectForKey("Naples")?.objectForKey("Item 0"))!

你能帮我解决这个问题吗? 提前致谢。

【问题讨论】:

  • I can't read the plist from the variables. 请在您的问题中显示您当前的尝试(您可以使用edit 按钮)。
  • 发布您的实际代码。
  • 该教程适用于数组。看起来你的 plist 根是字典
  • 你也不一致。你的一些数组项是数字,一些是字符串
  • Item 0 表示数组的第一项,所以它是objectAtIndex(0)

标签: ios swift plist


【解决方案1】:

这是一个仅使用 Swift 本机类型的纯 Swift 解决方案:

if let url = NSBundle.mainBundle().URLForResource("Dati", withExtension: "plist"), data = NSData(contentsOfURL: url) {
  do {
    let dictionary = try NSPropertyListSerialization.propertyListWithData(data, options: [], format: nil) as! [String:AnyObject]
    if let city = dictionary["Italia"]?["Naples"] as? [AnyObject] {
      let item0 = city[0] as! Int
      let item1 = city[1] as! String
    } else {
      print("Italia or Naples doesn't exist")
    }
  } catch let error as NSError {
    print("Property List Serialization Error: \(error)")
  }
} else {
  fatalError("File couldn't be read")
}

如果您将 plist 文件更改为仅使用 String 值,则可以避免某些类型转换

if let url = NSBundle.mainBundle().URLForResource("Dati", withExtension: "plist"), data = NSData(contentsOfURL: url) {
  do {
    let dictionary = try NSPropertyListSerialization.propertyListWithData(data, options: [], format: nil) as! [String:[String:[String]]]
    if let city = dictionary["Italia"]?["Naples"] {
      let item0 = city[0]
      let item1 = city[1]
    } else {
      print("Italia or Naples doesn't exist")
    }
  } catch let error as NSError {
    print("Property List Serialization Error: \(error)")
  }
} else {
  fatalError("File couldn't be read")
}

【讨论】:

  • 更容易转换为包含字符串数组字典的 [String:[String:[String]]] 字典。不要忘记提到他的文件有些项目是数字,有些是字符串。他需要修复它
  • 我承认这有点夸张,但 plist 中有一些 Int
  • 看起来他不需要两种不同的类型
  • 确实,这会让事情变得更容易,我更新了答案
  • @vadian:非常感谢。这正是 a 所寻找的。 :) 由于我的名誉,我不能接受答案,但我 200% 接受你的答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 2023-01-09
相关资源
最近更新 更多