Search String in NSDictionary store in NSMutableAr

2019-07-09 17:40发布

问题:

I am trying to search a String in NSDictionary stored in NSMutableArray

for (int k = 0; k < [onlyActiveArr count]; k++) {

    NSString *localID = [onlyActiveArr objectAtIndex:k];
    NSLog(@"%@",localID);

    int localIndex = [onlyActiveArr indexOfObject:localActiveCallID];
    NSLog(@"%d",localIndex);

    for (NSDictionary *dict in self.SummaryArr) {

        NSLog(@"%@",[dict objectForKey:@"ActiveID"]);

             if (![[dict objectForKey:@"ActiveID"] isEqualToString:localID]) {
                   NSLog(@"found such a key, e.g. %@",localID);

             }

    }
}

But I am getting

NSLog(@"found such a key, e.g. %@",localActiveCallID);

when the ID is still there in SummaryArr, I am checking if localID retrieved from onlyActiveArr is not present in dictionary.

Please suggest me how to overcome my problem.

回答1:

You cannot make a decision that a key is not present until you finish processing the entire dictionary. Make a boolean variable initially set to NO, and change it to YES if you find an item in the dictionary, like this:

BOOL found = NO;
for (NSDictionary *dict in self.SummaryArr) {
     NSLog(@"%@",[dict objectForKey:@"ActiveID"]);
     found = [[dict objectForKey:@"ActiveID"] isEqualToString:localID];
     if (found) break;
}
if (!found) {
    NSLog(@"found such a key, e.g. %@",localID);
}


回答2:

If you like predicates, then you can use the fact that accessing an inexistent key in a dictionary produces a nil value and make a predicate that filters out those dictionaries that have nil for your key.

If the count of the result is larger than zero, your key is somewhere in the array. It won't tell you where, though.

A snippet to show the idea:

NSPredicate *keyPred = [NSPredicate predicateWithFormat: @"NOT ActiveID == nil"];                  

BOOL found = [[self.SummaryArr filteredArrayUsingPredicate: keyPred] count] > 0;

I don't know how the performance stacks up, so if your data set is large you may want to check that the execution time is within your limits.