根据你的财产清单文件,你可以使用这个
// check the URL (URL related API is recommended)
if let tipsURL = NSBundle.mainBundle().URLForResource("Tips", withExtension:"plist") {
// read the property list file and cast the type to native Swift 'Dictionary'
let tipsPlist = NSDictionary(contentsOfURL: tipsURL) as! [String:AnyObject]
// get the array for key 'Category 1',
// casting the result to '[[String:String]]` avoids further type casting
let categoryArray = tipsPlist["Category 1"] as! [[String:String]]
// iterate thru the expected array and print all values for 'Title' and 'Tip'
for category in categoryArray {
print(category["Title"]!)
print(category["Tip"]!)
}
} else {
// if the plist file does not exist, give up
fatalError("Property list file Tips.plist does not exist")
}
或考虑在根对象
if let tipsURL = NSBundle.mainBundle().URLForResource("Tips", withExtension:"plist") {
let tipsPlist = NSDictionary(contentsOfURL: tipsURL) as! [String:AnyObject]
for (_, categoryArray) in tipsPlist {
for category in categoryArray as! [[String:String]] {
print(category["Title"]!)
print(category["Tip"]!)
}
}
} else {
fatalError("Property list file Tips.plist does not exist")
}
谢谢,这很好,正是我想要的,最后如何我会声明categoryArray,以便可以从其他函数访问它。 – Sami
实际上,包含类别('Category 1','Category 2'等)的对象是一个字典,而不是一个数组。在给定属性列表的问题中,如果'plist'是根对象,'NSArray * array = [plist objectAtIndex:0]'根本无法工作。 – vadian
刚刚实现的第一个对象也是一本字典,修正了问题。 – Sami