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.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With