【问题标题】:Retrieve data from plist从 plist 中检索数据
【发布时间】:2013-03-13 01:45:10
【问题描述】:

我有一个 plist,里面有一个数组,然后是一组字典元素?如何将 plist 中的数据检索到我的数组中?

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

【问题讨论】:

  • 为什么需要创建一个category_name数组?这是一个结构良好的数据。如果您想轻松访问它,请尝试使用属性 categoryName 和 categoryID 为类别创建模型类。这会更容易。

标签: ios xcode nsarray plist nsdictionary


【解决方案1】:

PropertyListDecoder 可用于将 plist 文件直接解码为对象。 详情看这个答案https://stackoverflow.com/a/60389142/5662893

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • // 直接获取 category_name 使用 [[arrayList objectAtIndex:0] valueForKey:@"category_name"]
    • 我为 Swift 2.0 添加了代码。请不要介意我
    • 没问题,我们在这里通过分享我们的知识来帮助其他人并解决问题。谢谢你的努力
    【解决方案3】:

    Targets => Copy bundle 资源中添加 .plist 文件 以上回复

    【讨论】:

      【解决方案4】:
      1. 从捆绑包或任何目录中获取文件路径
      2. 从从 plist 检索的字典中获取数组
      3. 获取存储在数组中的字典

        NSString *plistFilePath  = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"test.plist"];
        
        NSDictionary *list = [NSDictionary dictionaryWithContentsOfFile:plistFilePath];
        NSLog(@"%@",list);
        NSArray      *data = [list objectForKey:@"catlist"];
        for(int i=0; i< [data count]; i++)
        {
            NSMutableDictionary *details=[data objectAtIndex:i];
            NSLog(@"%@",[details objectForKey:@"category_name"]);
            NSLog(@"%@",[details objectForKey:@"cid"]);
        
        }
        

      【讨论】:

      • 好的。如何更改情节提要中的导航栏颜色?实际上我嵌入在导航控制器上,我想将其颜色更改为 RGB(20,60,72) 你知道吗?我试过了:self.navigationController.navigationBar.tintColor=[UIColor colorWithRed:26 green:62 blue:72 alpha :0];它不工作
      • @Bhargavi 我认为 plist 位于捆绑包中,而不是文档目录中。您可以考虑编辑答案。
      • @Naveen 评论用于讨论疑问/澄清。如果您有新问题,请单独提问。
      • @Anupdas 已在该目录中生成了一个 plist 文件,因此我已经给出了该路径。无论如何,我提到在任何一种情况下都从 bundle/ 目录中获取它
      • @Bhargavi 当我们做出假设时,也确实提供了替代代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      相关资源
      最近更新 更多