Ios – NSMutableArray check if object already exists

iosiphonensmutablearrayobjective-c

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 ?

Best Solution

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
}
Related Question