问题
plist1 is an array of 40 dictionaries, with 4 strings each. plist2 is also an array, but of 120 dictionaries with 2 strings each.
If I list all the teams in a hockey league in a table (populated from a certain key in plist1), say I choose the fifth one down. This pushes a new table. The 120 dictionaries in plist2 have two strings - each has one for a year of the league's history in order, and one for who won the championship that year. I want this second table to list only the years for which the the dictionary's second key is the same team name that was just selected in the first table, plist1. So, when I select team "5" from the first table, I'd expect to see only the years that team "5" won in the second table. The idea is that all the years will be present in plist2, but the irrelevant ones will be blocked in the actual table on-the-go.
How can I say "if the user selected team X, then show the years just for team X, not all the years."
Thank you!
回答1:
Actually you can do this kind of filtering quite nicely using NSPredicate
:
NSDictionary *testA = [NSDictionary dictionaryWithObjectsAndKeys:@"valA", @"key1", @"1", @"key2", nil];
NSDictionary *testB = [NSDictionary dictionaryWithObjectsAndKeys:@"valB", @"key1", @"2", @"key2", nil];
NSDictionary *testC = [NSDictionary dictionaryWithObjectsAndKeys:@"valC", @"key1", @"1", @"key2", nil];
NSDictionary *testD = [NSDictionary dictionaryWithObjectsAndKeys:@"valD", @"key1", @"3", @"key2", nil];
NSArray *testArr = [NSArray arrayWithObjects:testA, testB, testC, testD, nil];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"key2 == %@", @"1"];
NSArray *testFilter = [testArr filteredArrayUsingPredicate:pred];
NSLog(@"%@", testFilter);
This setup creates 4 dictionaries and an array of them. The filter expression now searches for all contained objects where key2
is equal to 1
, which should be testA
and testC
. And voila theres the output:
2011-11-24 18:57:07.822 testapp[9977:f803] (
{
key1 = valA;
key2 = 1;
},
{
key1 = valC;
key2 = 1;
}
)
This way you can create a predicate to filter by your team name and create a filtered version of your array. Generally this works on all kinds of object that support key-value coding (which NSDictionary
does, further info on that: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/BasicPrinciples.html#//apple_ref/doc/uid/20002170)
来源:https://stackoverflow.com/questions/8260693/objective-c-selectively-populate-table-from-plist-if-key-equals