誕生日と名前をキーとして持つ一連の辞書があります。同じ誕生日の名前の値を取得したい。
for (NSDictionary *contactDict in contactList) {
NSString *birthdayStr = [contactDict objectForKey:BIRTHDAY_KEY];
}
同じ誕生日の名前の配列を取得するにはどうすればよいですか。
これはあなたが探しているものですか?
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);
}
または、誕生日ごとに1つの名前配列のみが必要な場合:
// 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
)