我正在尝试从plist中获取信息。这是结构:
Root
-Dictionary
--Dictionary
---String
---String
--Dictionary
---String
---String
--Dictionary
---String
---String
编辑:和它的一个小样本:
<plist version="1.0">
<dict>
<key>introduction</key>
<dict>
<key>gfx</key>
<dict>
<key>titre</key>
<string>Introduction</string>
<key>color</key>
<string></string>
<key>miniLogo</key>
<string></string>
<key>bigLogo</key>
<string></string>
</dict>
...
所以基本上我要从嵌套在另一个字典中的字典中获取字符串值。
诀窍是,我想使用表格视图
到目前为止,我在这里:
let pathRoot = NSBundle.mainBundle().pathForResource("MyPLIST", ofType: "plist")
let rootRubrique = NSDictionary(contentsOfFile: pathRoot!)
我正在尝试获取这样的信息:
let rubriqueTitre = NSDictionary(contentsOfFile: pathRoot!)?.allKeys[indexPath.row].objectForKey("gfx")?.valueForKey("titre")
但也许问题出在我试图筛选它的方式上
label.text = imageRubrique! as! String
// And also tried :
label.text = "(imageRubrique!)"
我也试图获得其他值,只是为了尝试。这对我有用:
let rubriqueIndex = NSDictionary(contentsOfFile: pathRoot!)?.allKeys[indexPath.row]
label.text = rubriqueIndex as! String
我得到小写的"介绍",第一个。但我不想要那个值,我想要嵌套的那个!我快疯了!幸运的是,Stackoverflow存在!
在那之后,我将不得不找到一种方法来按正确的顺序对我的字典进行排序,这似乎是另一个大问题......
编辑:我解决了第一个问题。我创建了这个功能:
func getValueFromPLIST(rub: String, sousDossier : String, sousSousDossier : String?, value : String) -> String {
if sousSousDossier == nil {
return (NSDictionary(contentsOfFile: pathRoot!)!.objectForKey(rub)!.objectForKey(sousDossier)!.valueForKey(value) as? String)!
} else {
return (NSDictionary(contentsOfFile: pathRoot!)!.objectForKey(rub)!.objectForKey(sousDossier)!.objectForKey((sousSousDossier!))!.valueForKey(value) as? String)!
}
}
然后我将索引分配给一个常量:
let rubriqueIndex = NSDictionary(contentsOfFile: pathRoot!)?.allKeys[indexPath.row]
然后我通过 func 生成整个值 ForKey:
let rubriquePathTitre = getValueFromPLIST(String(rubriqueIndex!), sousDossier: "gfx", sousSousDossier: nil, value: "titre")
我不知道为什么它会使用这个技巧,但它正在工作,而且还不错,因为我在其他地方需要索引。但不幸的是,我认为我将不得不使用其他东西,例如"rank"或"ID"值来对我的字典进行排序。所以整个事情最后都没用了哈哈!
您可以使用UITableView
索引代替迭代索引
// *** Access data from plist ***
let pathRoot = NSBundle.mainBundle().pathForResource("MyPLIST", ofType: "plist")
// *** Get Root element of plist ***
let rootRubrique = NSDictionary(contentsOfFile: pathRoot!)
// *** get Next element which is `Introduction` holding all other objects ***
let objIntro:NSDictionary = rootRubrique!.objectForKey("introduction") as! NSDictionary
选项 1:使用 Index 循环访问所有对象
for var i = 1; i <= objIntro.allValues.count; ++i
{
print("Index[(i)] (objIntro.allValues[0])")
}
在您的情况下使用索引路径进行访问
let obj = (objIntro.allValues[indexPath.row])
选项 2:遍历字典的所有值
for (key, value) in objIntro
{
print("key: "(key as! String)" obj : (value)")
}