根據你的財產清單文件,你可以使用這個
// 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