NSMutableArray check if object already exists NSMutableArray check if object already exists ios ios

NSMutableArray check if object already exists


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}


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.


Use NSPredicate.

NSArray *list = [[appDelegate.list copy] autorelease];for (Item *item in addList) {    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"iName MATCHES %@", item.iName];    NSArray *filteredArray = [list filteredArrayUsingPredicate:predicate];    if ([filteredArray count] > 0) [appDelegate insertItem:item];}