Search code examples
iphonensmutablearrayplist

Get plist into array


I have seen lots of similar questions but nothing is working for me. I need to get the contents of my plist into an NSMutableArray.

My plist is a dictionary containing 1 array. This array has multiple dictionaries. I have used the same code in another app and it worked:

    NSString *path = [[NSBundle mainBundle] pathForResource:@"TeamsData" ofType:@"plist"];
NSMutableArray *temp = [[NSMutableArray arrayWithContentsOfFile:path] retain];
NSLog(@"TEMP: %@", temp);
data = [NSMutableArray arrayWithArray:[[temp objectAtIndex:0] objectForKey:@"Teams"]];

temp returns NULL but I can't figure out why. Any ideas?


Update

I actually discovered why my code was working in one app and not the other. In the app it did work in when I opened the plist as source the entire plist was enclosed in an array. This didn't show up when I viewed it in the standard xcode plist editor though. So to get the same code working on the new plist I could just open it as source and enclose it in array tags.


Solution

  • You say you have a plist which is a dictionary containing an array of dictionaries, but you try to read the file from the bundle as if it were an array. Try using NSDictionary's -initWithContentsOfFile: instead.

    The array should have a key in the plist's dictionary, something like the folllowing:

    ...
    <dict>
        <key>Teams</key>
        <array>
            <dict>
                ...
            </dict>
            ...
        </array>
    </dict>
    

    So extracting the array should be a matter of asking the plist dictionary for the object with key Teams:

    teamsArray = [ plistDictionary objectForKey: @"Teams" ];