Search code examples
xmliphone-sdk-3.0nsarrayplistnsdictionary

extract data from Plist to array and dictionary


I made a plist that looks like that:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList 1.0.dtd">
<plist version="1.0">
<array>
<array>
    <dict>
        <key>Company</key>
        <string>xxx</string>
        <key>Title</key>
        <string>VP Marketing</string>
        <key>Name</key>
        <string>Alon ddfr</string>
    </dict>
    <dict>
        <key>Name</key>
        <string>Adam Ben Shushan</string>
        <key>Title</key>
        <string>CEO</string>
        <key>Company</key>
        <string>Shushan ltd.</string>
    </dict>
</array>
<array>
    <dict>
        <key>Company</key>
        <string>xxx</string>
        <key>Title</key>
        <string>CTO</string>
        <key>Name</key>
        <string>Boaz frf</string>
    </dict>
</array>
</array>
</plist>

Now I want to extract the data like that (all the 'A' for key "Name" to one section and all the 'B' "Name" to other one):

NSString *plistpath = [[NSBundle mainBundle] pathForResource:@"PeopleData" ofType:@"plist"];
NSMutableArray *attendees = [[NSMutableArray alloc] initWithContentsOfFile:plistpath];


listOfPeople = [[NSMutableArray alloc] init];//Add items

NSDictionary *indexADict = [NSDictionary dictionaryWithObject:[[attendees objectAtIndex:0] objectForKey:@"Name"] forKey:@"Profiles"];


NSDictionary *indexBDict = [NSDictionary dictionaryWithObject:[[attendees objectAtIndex:1] objectForKey:@"Name"]  forKey:@"Profiles"];

[listOfPeople addObject:indexADict];
[listOfPeople addObject:indexBDict];

This in order to view them in sectioned tableView.

I know that the problem is here:

NSDictionary *indexADict = [NSDictionary dictionaryWithObject:[[attendees objectAtIndex:0] objectForKey:@"Name"] forKey:@"Profiles"];

But I just can't figure how to do it right.

Thanks.


Solution

  • You have a plist containing an array of arrays of dictionaries.

    NSDictionary *indexADict =  (NSDictionary *)[(NSArray *)[attendees objectAtIndex:0] objectAtIndex:0];
    

    The key (Profiles) you are requesting doesn't exist in your plist. There is no point in constructing a new dictionary to hold the existing dictionary from your plist.

    If you have an array of dictionaries (or any key value coding compliant objects) you can extract an array of "Name" attributes by:

    NSArray *names = [array valueForKey:@"Name"];