4

The title is a bit confusing...I'll explain

I have an NSMutableArray I am populating with NSMutableDictionary objects. What I am trying to do is before the dictionary object is added to the array, I need to check whether any of the dictionaries contain a value equal to an id that is already set.

Example:

Step 1: A button is clicked setting the id of an object for use in establishing a view.

Step 2: Another button is pressed inside said view to save some of its contents into a dictionary, then add said dictionary to an array. But if the established ID already exists as a value to one of the dictionaries keys, do not insert this dictionary.

Here is some code I have that is currently not working:

-(IBAction)addToFavorites:(id)sender{
    NSMutableDictionary *fav = [[NSMutableDictionary alloc] init];
    [fav setObject:[NSNumber numberWithInt:anObject.anId] forKey:@"id"];
    [fav setObject:@"w" forKey:@"cat"];

    if ([dataManager.anArray count]==0) {     //Nothing exists, so just add it
        [dataManager.anArray addObject:fav];
    }else {
        for (int i=0; i<[dataManager.anArray count]; i++) {
            if (![[[dataManager.anArray objectAtIndex:i] objectForKey:@"id"] isEqualToNumber:[NSNumber numberWithInt:anObject.anId]]) {
                [dataManager.anArray addObject:fav];
            }       
        }
    }
    [fav release];
}
rson
  • 1,455
  • 2
  • 24
  • 43
  • What version of iOS do you want your code to run on? If you are using iOS 4.0+ than blocks make this pretty easy. – kubi Sep 14 '10 at 15:02
  • No need for the special "empty" case. And your logic inside the loop is wrong. You first need to check if it is in *any* of them, and after the loop, add if necessary. – Eiko Sep 14 '10 at 15:09
  • This is actually running on the iPad, iOS 3.2. – rson Sep 14 '10 at 15:33

1 Answers1

7

One fairly easy way to do this kind of check is to filter the array using an NSPredicate. If there's no match, the result of filtering will be an empty array. So for example:

NSArray *objs = [dataManager anArray];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %@", [NSNumber numberWithInt:i]];
NSArray *matchingObjs = [objs filteredArrayUsingPredicate:predicate];

if ([matchingObjs count] == 0)
{
    NSLog(@"No match");
}
jlehr
  • 15,557
  • 5
  • 43
  • 45