Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In NSMutableArray methods, removeObject: vs removeObjectIdenticalTo:

Tags:

objective-c

With regards to a NSMutableArray, what is the difference between removeObject: and removeObjectIdenticalTo:

The wording in the API Reference seems very similar:

rO: Removes all occurrences in the receiver of a given object

rOIT: Removes all occurrences of a given object in the receiver

What am I missing?

UPDATE: I mean, how would I choose between them.

like image 912
willc2 Avatar asked Mar 28 '09 03:03

willc2


2 Answers

removeObjectIdenticalTo: will remove the object that is being pointed to, removeObject: will run a isEqual: on all items in the array and remove it if it returns true.

Edit:

You should use removeObjectIdenticalTo: if you know you have the same object (like for NSViews or similar), and removeObject: for strings and objects where it may not be the same object, but should be considered equal for practical purposes.

like image 97
cobbal Avatar answered Nov 15 '22 17:11

cobbal


@cobbal Really great answer :) After seeing your answer I really understood the difference. But at first it seemed little confusing for me since I'm a newbie to Objective-C programming so I just want to enhance your answer by providing an example. Hope it helps other newbies when they look at the example :)

#import<Foundation/Foundation.h>
int main()
{   int i;
    printf("Enter 1 to perform removeObject function.\n Enter 2 to perform removeObjectIdenticalTo functionality.\n ");
    scanf("%d",&i);
    @autoreleasepool{
    NSString* color;// int count;
    NSString * s1 = [NSMutableString stringWithString: @"Red"];
    NSString * s2 = [NSMutableString stringWithString: @"Yellow"];
    NSString * s3 = [NSMutableString stringWithString: @"Red"];
    NSString * s4 = [NSMutableString stringWithString: @"Cyan"];
    NSMutableArray * myColors = [NSMutableArray arrayWithObjects: s1,s2,s3,s4,nil];

    if(i == 1)
    {
        [myColors removeObject: s1];    //will remove both s1 and s3 object because their contents are same
//we can also use [myColors removeObject: @"Red"]; instead of above statement. However the functionality remains same . 
        for(color in myColors)NSLog(@"%@",color); 
    }

    else if (i == 2){
        [myColors removeObjectIdenticalTo: s1];  //deletes only s1 object in the array myColor  
        for(color in myColors)NSLog(@"%@",color);
    }

    }
    return 0;
    }

PS : This is just a example. U can find the answer in @cobbal 's answer.

like image 42
iamyogish Avatar answered Nov 15 '22 17:11

iamyogish