加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ios – 从plist中检索数据

发布时间:2020-12-15 01:48:28 所属栏目:百科 来源:网络整理
导读:我有一个plist,里面有一个数组,然后是一组字典元素?如何从plist中检索数据到我的数组? 如何在一个数组中获取类别名称? 解决方法 Objective-C的 // Read plist from bundle and get Root Dictionary out of itNSDictionary *dictRoot = [NSDictionary dict
我有一个plist,里面有一个数组,然后是一组字典元素?如何从plist中检索数据到我的数组?

如何在一个数组中获取类别名称?

解决方法

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"]);
}];

迅速

// 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"])")
    })
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读