NSMutableArray check if object already exists

79,001

Solution 1

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.

Solution 2

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 3

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];
}

Solution 4

Did you try indexOfObject:?

-(void)doneClicked{
    for (Item *item in addList){
        if([appDelegate.list indexOfObject:item] == NSNotFound){
            [appDelegate insertItem:item];
        }
}

UPDATE: You have a logical mistake, not mistake in code. assume the first array is ['a', 'b', 'c'], and the second is ['a', 'x', 'y', 'z']. When you iterate with 'a' through the second array it won't add 'a' to second array in the first iteration (compare 'a' with 'a') but will add during the second (compare 'a' with 'x'). That is why you should implement isEqual: method (see below) in your 'Item' object and use the code above.

- (BOOL)isEqual:(id)anObject {
    if ([anObject isKindOfClass:[Item class]])
        return ([self.iName isEqualToString:((Item *)anObject).iName]);
    else
        return NO;
}

Solution 5

Have a look at NSSet. You can add objects and the object will only be added if the object is unique. You can create a NSSet from an NSArray or vise versa.

Share:
79,001

Related videos on Youtube

Neelesh
Author by

Neelesh

iOS dev

Updated on April 13, 2020

Comments

  • Neelesh
    Neelesh about 4 years

    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 ?

    • knuku
      knuku almost 13 years
      It is a logic mistake, see my answer
  • Neelesh
    Neelesh almost 13 years
    @NR4TR: i want to compare the names alone. Not the entire object
  • Neelesh
    Neelesh almost 13 years
    First, I want to compare the names alone and not the entire object.
  • knuku
    knuku almost 13 years
    Consider reading documentation about isEquals method, it could help
  • Simon Lee
    Simon Lee almost 13 years
    Yes, the idea of overriding the isEquals is that you can then define what you consider 'equal'. Normally the runtime will look at two objects and if they are not the same instance will return false. By overriding the isEquals method you can say 'actually I don't care if the OBJECTS are not the same, in my eyes, these two items are the same if the name matches.'
  • Neelesh
    Neelesh almost 13 years
    Yes i get it now. But when i use the code you have updated, I get the following error [Item isEqualToString:]: unrecognized selector sent to instance 0x712ee70
  • JeremyP
    JeremyP almost 13 years
    +1 nice answer. Also avoids the mutating collection exception that would happen if the method used in the question actually worked.
  • knuku
    knuku almost 13 years
    Check your isEqual: method implementation inside your Item class
  • Neelesh
    Neelesh almost 13 years
    sorry, I do not seem to follow. Item is a class that i created myself and I do not have an isEqual method at all. Can you please help me in detail ?
  • knuku
    knuku almost 13 years
    see updates. just paste this isEqual: method to your Item implementation
  • Neelesh
    Neelesh almost 13 years
    I tried the above edited solution. First thing, the program crashes without showing any error. Secondly, the Item is added even if it exists in the datasource list
  • Neelesh
    Neelesh almost 13 years
    I still get the same error. [Item isEqualToString:]: unrecognized selector sent to instance 0x712ee70
  • knuku
    knuku almost 13 years
    please read docs carefully and try to do some debugging yourself, it's really hard to do debugging via comments
  • Neelesh
    Neelesh almost 13 years
    @simon: thanks for the answer. But still the program crashes :( I am just banging my head now :(
  • EmptyStack
    EmptyStack almost 13 years
    @Narayanan, Can you tell in which line the program crashes?
  • Neelesh
    Neelesh almost 13 years
    I will try debugging :( I thought this should be simple
  • Neelesh
    Neelesh almost 13 years
    @simon: It crashes where we create the predicate. [NSComparisonPredicate isEqualToString:]: unrecognized selector sent to instance 0x7154070
  • EmptyStack
    EmptyStack almost 13 years
    @Narayanan, Remove the single quotes ' from the predicate format and check. I've edited my answer.
  • Neelesh
    Neelesh almost 13 years
    @simon: I am sorry. The program crashes. :( :(
  • EmptyStack
    EmptyStack almost 13 years
    @Narayanan, Alright. Check if the objects in the addList are getting release somewhere or you have some other problem.
  • Neelesh
    Neelesh almost 13 years
    No. They are not released anywhere else
  • Neelesh
    Neelesh almost 13 years
    @simon: I am not able to figure it out :(
  • EmptyStack
    EmptyStack almost 13 years
    @Narayanan, Try to print the iNames in the addList and appDelegate.list and check if they are valid.