在这种情况下如何定义NSPredicate?

时间:2012-08-21 15:10:56

标签: objective-c

我正在尝试使用NSPredicate获得以下目标值。

但是,我在使用NSPredicate语法时遇到了困难。

我希望在源数据中获取姓名最大年龄的姓氏列表,而不会重复。

请任何人的帮助......

NSDictionary *dic1 = [NSDictionary dictionaryWithObjects:@[@"James",    @10] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:@[@"Robert",   @15] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjects:@[@"Robert",   @10] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic4 = [NSDictionary dictionaryWithObjects:@[@"James",    @20] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic5 = [NSDictionary dictionaryWithObjects:@[@"David",    @20] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic6 = [NSDictionary dictionaryWithObjects:@[@"Walter",   @30] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic7 = [NSDictionary dictionaryWithObjects:@[@"Nicholas", @30] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic8 = [NSDictionary dictionaryWithObjects:@[@"David",    @30] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic9 = [NSDictionary dictionaryWithObjects:@[@"David",    @30] forKeys:@[@"LastName", @"Age"]];

NSArray *persons = [NSArray arrayWithObjects:dic1, dic2, dic3, dic4, dic5, dic6, dic7, dic8, dic9, nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:???]

NSArray *result = [persons filteredArrayUsingPredicate:predicate];
NSLog(@"result : %@",result);



source data
LastName          age
James              10
Robert             15
Robert             10
James              20
David              20
Walter             30
Nicholas           30
David              30
David              30

target data
James              20
Robert             15
David              30
Walter             30
Nicholas           30

1 个答案:

答案 0 :(得分:0)

我不相信这可以用谓词来完成。我会通过使用键“Age”对数组进行排序,然后循环遍历该数组,将第一条记录添加到结果数组,然后检查下一条记录是否与第一条记录具有相同的LastName,如果是这样,那么我会这样做。将该值添加到最终数组中。像这样:

NSArray *sorters = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Age" ascending:NO]];
    NSArray *sorted = [persons sortedArrayUsingDescriptors:sorters];
    NSMutableArray *result = [NSMutableArray array];
    for (id dict in sorted) {
        if (! [[result valueForKey:@"LastName"] containsObject:[dict valueForKey:@"LastName"]]) {
            [result addObject:dict];
        }
    }
    NSLog(@"%@",result);