Retrieve data from plist
Asked Answered
S

4

7

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?

plist

How can I get category names in one array?

Streusel answered 23/3, 2013 at 4:16 Comment(1)
Why do you need to make an array of category_name? This is a well structured data. If you want to access it easily, try making a model class for category with properties categoryName and categoryID. This would be easier.Striated
R
31

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 Code

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"])")
    })
}
Runoff answered 23/3, 2013 at 4:22 Comment(3)
// To Directly fetch category_name use [[arrayList objectAtIndex:0] valueForKey:@"category_name"]Runoff
I have added a code for Swift 2.0. Please don't mind meDanika
No problem, here we are to help other & solve problem by sharing our knowledge. thx for your effortsRunoff
B
5
  1. Get your file path from bundle or from any directory
  2. Get the array from dictionary retrieved from plist
  3. Get dictionary stored in array

    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"]);
    
    }
    
Brien answered 23/3, 2013 at 4:22 Comment(11)
OK. how can i change the navigationbar color in storyboard?? actually i embedded on navigation controller and i wanna change its color to RGB(20,60,72) do you know??i tried that :self.navigationController.navigationBar.tintColor=[UIColor colorWithRed:26 green:62 blue:72 alpha:0]; its not workingStreusel
@Bhargavi I think the plist is in the bundle rather than the documents directory. You may consider editing the answer.Striated
@Streusel Comments are for discussing doubts/clarification. If you have a new question ask as a seperate quesion.Striated
@Striated have generated one plist file in that directory so I hace given that path. Anyways I mentioned to fetch it from bundle/ directory in either caseNarcolepsy
@Bhargavi When we make assumptions do provide the alternatives codes as well.Striated
One comment, they won't be mutable dictionaries.Insulate
@Streusel I agree with Anupdas you should post question. Though for your answer try this self.navigationController.navigationBar.tintColor=[UIColor colorWithRed:26/255.0 green:62/255.0 blue:72/255.0 alpha:1];Narcolepsy
@thanks Bhargavi..I tried to post question ,but it shows"not meets our quality standards" i dnt like thatStreusel
@ITs WOrking...oh NOw i realise its a cgfloat so we have to use 255.0 ...thabks Bhargavi...Streusel
@Streusel its also about alpha:0.. you need to set alpha:1. alpha is used for transparency.Narcolepsy
@Bhargavi Please check this question https://mcmap.net/q/1474852/-usernotes-in-iosStreusel
M
0

PropertyListDecoder can be used to decode plist file directly to object. For details see this answer https://mcmap.net/q/1474853/-how-to-read-plist-without-using-nsdictionary-in-swift

Maltz answered 25/2, 2020 at 7:9 Comment(0)
W
-1

do add .plist file in Targets => Copy bundle resource With the above in reply

Whitnell answered 15/10, 2013 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.