开发者

Stepping thru a plist to get at info

开发者 https://www.devze.com 2022-12-30 12:48 出处:网络
If I\'ve got a plist set up like this KeyTypeValue RootArray Item 0Dictionary -TitleStringPart One -Description StringWelcome to part one. Have fun

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
 开发者_StackOverflowItem 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?


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).


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消