Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 286
Neelesh Avatar asked Jun 09 '11 10:06

Neelesh


2 Answers

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 } 
like image 143
Black Tiger Avatar answered Sep 25 '22 02:09

Black Tiger


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.

like image 21
Neelesh Avatar answered Sep 22 '22 02:09

Neelesh