0

我有一个字典数组,其中包含生日和姓名作为键。我想检索具有相同生日的名称的值。

    for (NSDictionary *contactDict in contactList) {
            NSString *birthdayStr = [contactDict objectForKey:BIRTHDAY_KEY];
}

我应该怎么做才能获得相同生日的名称数组。

4

1 回答 1

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
)
于 2013-03-17T18:47:41.913 回答