Search code examples
objective-cxcodefor-loopnsarraynsdictionary

Search String in NSDictionary store in NSMutableArray


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.


Solution

  • 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);
    }