从plist中检索数据 [英] Retrieve data from plist
本文介绍了从plist中检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个plist,里面有一个数组,然后是一组字典元素?如何从plist到我的数组中检索数据?
I have a plist and inside that an array and then set of dictionary elements? How can I retrieve data from the plist to my array?
如何在一个数组中获取类别名称?
How can I get category names in one array?
推荐答案
Objective-C
// Read plist from bundle and get Root Dictionary out of it
NSDictionary *dictRoot = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
// Your dictionary contains an array of dictionary
// Now pull an Array out of it.
NSArray *arrayList = [NSArray arrayWithArray:[dictRoot objectForKey:@"catlist"]];
// Now a loop through Array to fetch single Item from catList which is Dictionary
[arrayList enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop) {
// Fetch Single Item
// Here obj will return a dictionary
NSLog(@"Category name : %@",[obj valueForKey:@"category_name"]);
NSLog(@"Category id : %@",[obj valueForKey:@"cid"]);
}];
Swift
// Read plist from bundle and get Root Dictionary out of it
var dictRoot: [NSObject : AnyObject] = [NSObject : AnyObject].dictionaryWithContentsOfFile(NSBundle.mainBundle().pathForResource("data", ofType: "plist"))
// Your dictionary contains an array of dictionary
// Now pull an Array out of it.
var arrayList: [AnyObject] = [AnyObject].arrayWithArray((dictRoot["catlist"] as! String))
// Now a loop through Array to fetch single Item from catList which is Dictionary
arrayList.enumerateObjectsUsingBlock({(obj: AnyObject, index: UInt, stop: Bool) -> Void in
// Fetch Single Item
// Here obj will return a dictionary
NSLog("Category name : %@", obj["category_name"])
NSLog("Category id : %@", obj["cid"])
})
Swift 2.0代码
var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("data", ofType: "plist") {
myDict = NSDictionary(contentsOfFile: path)
}
let arrayList:Array = myDict?.valueForKey("catlist") as! Array<NSDictionary>
print(arrayList)
// Enumerating through the list
for item in arrayList {
print(item)
}
Swift 3.0
// Read plist from bundle and get Root Dictionary out of it
var dictRoot: NSDictionary?
if let path = Bundle.main.path(forResource: "data", ofType: "plist") {
dictRoot = NSDictionary(contentsOfFile: path)
}
if let dict = dictRoot
{
// Your dictionary contains an array of dictionary
// Now pull an Array out of it.
var arrayList:[NSDictionary] = dictRoot?["catlist"] as! Array
// Now a loop through Array to fetch single Item from catList which is Dictionary
arrayList.forEach({ (dict) in
print("Category Name \(dict["category_name"]!)")
print("Category Id \(dict["cid"])")
})
}
这篇关于从plist中检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文