简体   繁体   中英

Objective C: Filter out results from NSMutableArray by a dictionary key's value?

I have a NSMutableArray like this :

(
        {
        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;
    }
)

Now how can I sort this NSMutableArray to get the results corresponding to State "Florida" I expect to get

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

I went for this code,but it displays again the prevous four dictionaries .

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

Try using a comparator block:

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

Alternatively, you can use a predicate as well:

NSPredicate *p = [NSPredicate predicateWithFormat:@"State = %@", @"Florida"];
NSArray *filtered = [array filteredArrayUsingPredicate:p];

If your array contains dictionary then you can use NSPredicate to filter out your array as follows:

NSPredicate *thePredicate = [NSPredicate predicateWithFormat:@"State CONTAINS[cd] Florida"];
theFilteredArray = [theArray filteredArrayUsingPredicate:thePredicate];

Assuming your array name is : arr

This one of the typical way to find, although a bit obsolete way....

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

Using predicates and blocks are already posted :)

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"State = %@", @"Florida"];
NSArray *filteredArray = [arr filteredArrayUsingPredicate:predicate];
NSLog(@"filtered ->%@",filteredArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM