我有一系列字典,其中包含Birthday和Name作为键。我想检索具有相同生日的名称的值。
for (NSDictionary *contactDict in contactList) {
NSString *birthdayStr = [contactDict objectForKey:BIRTHDAY_KEY];
}
我应该怎样做才能获得同一个生日的名字数组。
答案 0 :(得分:4)
这是你在找什么?
for (NSDictionary *contactDict in contactList) {
NSString *birthdayStr = [contactDict objectForKey:BIRTHDAY_KEY];
// indexes of all array objects with same birthday:
NSIndexSet *matching = [contactList indexesOfObjectsPassingTest:^BOOL(NSDictionary *contactDict, NSUInteger idx, BOOL *stop) {
return [[contactDict objectForKey:BIRTHDAY_KEY] isEqualToString:birthdayStr];
}];
NSArray *matchingNames = [[contactList objectsAtIndexes:matching] valueForKey:NAME_KEY];
NSLog(@"%@", matchingNames);
}
或者,如果每个不同的生日只需要一个名称数组:
// Set of all distinct birthdays:
NSSet *allBirthdays = [NSSet setWithArray:[contactList valueForKey:BIRTHDAY_KEY]];
for (NSString *birthdayStr in allBirthdays) {
NSLog(@"birthday: %@", birthdayStr);
NSIndexSet *matching = [contactList indexesOfObjectsPassingTest:^BOOL(NSDictionary *contactDict, NSUInteger idx, BOOL *stop) {
return [[contactDict objectForKey:BIRTHDAY_KEY] isEqualToString:birthdayStr];
}];
NSArray *matchingNames = [[contactList objectsAtIndexes:matching] valueForKey:NAME_KEY];
NSLog(@"names: %@", matchingNames);
}
示例数据的输出:
birthday: 1/12/13
names: (
A,
B
)
birthday: 2/12/13
names: (
C
)