4

我有一个这样的 NSMutableArray:

(
        {
        City = "Orlando";
       Name = "Shoreline Dental";
        State = Florida;
    },
        {
        City = "Alabaster ";
        Name = Oxford Multispeciality;
        State = Alabama;
    },
        {
        City = Dallas;
        Name = "Williams Spa";
        State = Texas;
    },
        {
        City = "Orlando ";
        Name = "Roast Street";
        State = Florida;
    }
)

现在我如何对这个 NSMutableArray 进行排序以获得与我期望得到的州“佛罗里达”相对应的结果

(
        {
        City = "Orlando";
       Name = "Shoreline Dental";
        State = Florida;
    },
 {
        City = "Orlando ";
        Name = "Roast Street";
        State = Florida;
    }
)

我去找了这段代码,但它再次显示了之前的四个字典。

NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Florida" ascending:YES];
       NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor];
        NSArray * sortedArray = [arr sortedArrayUsingDescriptors:descriptors];
4

3 回答 3

7

尝试使用比较器块:

NSIndexSet *indices = [array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
    return [[obj objectForKey:@"State"] isEqualToString:@"Florida"];
}];
NSArray *filtered = [array objectsAtIndexes:indices];

或者,您也可以使用谓词:

NSPredicate *p = [NSPredicate predicateWithFormat:@"State = %@", @"Florida"];
NSArray *filtered = [array filteredArrayUsingPredicate:p];
于 2012-12-24T08:01:04.047 回答
2

如果您的数组包含字典,那么您可以使用 NSPredicate 过滤掉您的数组,如下所示:

NSPredicate *thePredicate = [NSPredicate predicateWithFormat:@"State CONTAINS[cd] Florida"];
theFilteredArray = [theArray filteredArrayUsingPredicate:thePredicate];
于 2012-12-24T08:04:27.660 回答
1

假设您的数组名称是:arr

这是一种典型的查找方式,虽然有点过时....

for (NSDictionary *dict in arr) {
    if ([[dict objectForKey:@"State"]isEqualToString:@"Florida"]) {
        [filteredArray addObject:dict];
    }
}
NSLog(@"filteredArray->%@",filteredArray);

使用谓词和块已经发布:)

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"State = %@", @"Florida"];
NSArray *filteredArray = [arr filteredArrayUsingPredicate:predicate];
NSLog(@"filtered ->%@",filteredArray);
于 2012-12-24T08:23:36.693 回答