NSMutableArray check if object already exists

I am not sure how to go about this. I have an NSMutableArray (addList) which holds all the items to be added to my datasource NSMutableArray.

I now want to check if the object to be added from the addList array already exists in the datasource array. If it does not exist add the item, if exists ignore.

Both the objects have a string variable called iName which i want to compare.

Here is my code snippet

-(void)doneClicked{
    for (Item *item in addList){
        /*
        Here i want to loop through the datasource array 
        */
        for(Item *existingItem in appDelegate.list){
            if([existingItem.iName isEqualToString:item.iName]){
                // Do not add
            }
            else{
                [appDelegate insertItem:item];
            } 
        }
}

But i find the item to be added even if it exists.

What am i doing wrong ?


Solution 1:

There is a very useful method for this in NSArray i.e. containsObject.

NSArray *array;
array = [NSArray arrayWithObjects: @"Nicola", @"Margherita",                                       @"Luciano", @"Silvia", nil];
if ([array containsObject: @"Nicola"]) // YES
{
    // Do something
}

Solution 2:

I found a solution, may not be the most efficient of all, but atleast works

NSMutableArray *add=[[NSMutableArray alloc]init];

for (Item *item in addList){
        if ([appDelegate.list containsObject:item])
            {}
        else
            [add addObject:item];
}

Then I iterate over the add array and insert items.