views:

55

answers:

2

If I've got a plist set up like this

Key           Type         Value
Root          Array
 Item 0       Dictionary  
 -Title       String       Part One
 -Description String       Welcome to part one. Have fun
 Item 1       Dictionary  
 -Title       String       Part Two
 -Description String       Welcome to part two. Fun too.
 Item 2       Dictionary  
 -Title       String       Part Three
 -Description String       Welcome to part three. It's free
 Item 3       Dictionary  
 -Title       String       Part Four
 -Description String       It's part four. No more

How would I step thru to put all the titles in one array, and all the descriptions into another?

+1  A: 

See the Collections Programming Topics for Cocoa

NSArray *items = [[NSArray alloc] initWithContentsOfFile:@"items.plist"];
NSMutableArray *titles = [[NSMutableArray alloc] init];
NSMutableArray *descriptions = [[NSMutableArray alloc] init];

for (NSDictionary *item in items) {
    [titles addObject:[item objectForKey:@"Title"]];
    [descriptions addObject:[item objectForKey:@"Description"]];
}

[items release];

// Do something with titles and descriptions

[titles release];
[descriptions release];
falconcreek
+4  A: 

Oooooooo this is where the awesomeness of Key-Value Coding shines.

NSArray * plistContents = [NSArray arrayWithContentsOfFile:pathToPlist];
NSArray * titles = [plistContents valueForKey:@"Title"];
NSArray * descriptions = [plistContents valueForKey:@"Description"];

The secret here is that invoking valueForKey: on an array returns a new array of objects that contains the result of invoking valueForKey: on each thing in the array. And invoking valueForKey: on a dictionary can be equivalent to using objectForKey: (if the key you're using is a key in a key-value pair). For more info, see the documentation.

One word of caution: Using a key of "Description" can potentially cause you to tear some hair out when you start seeing weird results, because one misspelling and you'll actually start invoking the -description method on each dictionary (which is not what you want).

Dave DeLong
Dave DeLong rocks! I was seconds away from posting. Awesome!
Jordan