【问题标题】:How do I access an array and it objects within a plist with SWIFT?如何使用 SWIFT 在 plist 中访问数组及其对象?
【发布时间】:2014-07-20 08:52:11
【问题描述】:

早安,

我已经环顾了这里和谷歌,但似乎找不到答案。我有一个名为 SoundsList 的 plist - 在根级别它是一个字典(默认),第一个项目是一个名为 Sounds 的数组,然后它的项目都是字符串。

我希望能够访问数组中的项目,但似乎无法找到如何执行此操作。

let path = NSBundle.mainBundle().pathForResource("SoundsList", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path)

到目前为止,我设法找到了上面的代码,它为我提供了路径和字典部分 - 我设法在另一篇文章中找到了这段代码 - Swift - Read plist

问候,

戴夫

【问题讨论】:

    标签: swift plist ios8


    【解决方案1】:

    是的,你是对的

    //Gives path of plist
    let path = NSBundle.mainBundle().pathForResource("SoundsList", ofType: "plist")
    //you are intializing dictionary from plist
    let dict = NSDictionary(contentsOfFile: path)
    

    此代码为您提供字典。您可以打印字典的内容

    println(dict)
    

    正如你描述的字典结构应该是这样的

    {
     "Sounds":(
                "sound1",
                 "sound2"
              )
    
    }
    

    所以要访问您可以使用的声音列表

      var soundsList = dict["Sounds"]
      println(soundList) //this will print your soundList
    

    您可以使用迭代到每个对象

    for item in soundsList {
       println(item)  //print sound1 and sound2
    }
    

    您应该参考 swift guide https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html 中的集合类型

    【讨论】:

    • 阅读以上内容并查看该链接后,我对其进行了调整,因为 Xcode 给出了“推理”错误。 var soundList : Array = dict["Sounds"] as Array
    猜你喜欢
    • 2017-08-08
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多