2

I am using one NSMutableArray with same string object.

Here is the code

NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:@"hello",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",nil];
NSObject *obj = [arr objectAtIndex:2];    
[arr removeObject:obj];       
NSLog(@"%@",arr);

When i try to remove 3rd object of array, its removing all object with "hi" string. I am not getting why its happening.
my doubt is while removing object, NSMutableArray match string or address.

sachin
  • 1,015
  • 4
  • 11
  • 24

3 Answers3

4

It's because you're using removeObject which removes all objects that are "equal" to the one you pass in. As per this Apple documentation:

This method uses indexOfObject: to locate matches and then removes them by using removeObjectAtIndex:. Thus, matches are determined on the basis of an object’s response to the isEqual: message. If the array does not contain anObject, the method has no effect (although it does incur the overhead of searching the contents).

You're seeing the effects of literal strings here where each of those @"hi" objects will turn out to be the same object just added many times.

What you really want to do is this:

NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:@"hello",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",nil];
[arr removeObjectAtIndex:2];
NSLog(@"%@",arr);

Then you're specifically removing the object at index 2.

Community
  • 1
  • 1
mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
  • 1
    Typo alert: `removeObjectAtInded` should have an `x` at the end :-). – Gareth McCaughan Feb 08 '12 at 14:21
  • Correction: 'removeObject' method does not remove all objects that are equal. Rather, it removes only one occurrence of it. In order to remove all objects that are "equal", we must use 'removeObjectIdendicalTo' method. – santobedi Aug 04 '17 at 07:26
3

According to https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html

removeObject:

Removes all occurrences in the array of a given object.

which is exactly the behaviour you're seeing. If you want to remove the object at a particular position, you want removeObjectAtIndex:.

Community
  • 1
  • 1
Gareth McCaughan
  • 19,888
  • 1
  • 41
  • 62
3
NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:@"hello",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",@"hi",nil];
NSUInteger obj = [arr indexOfObject:@"hi"];  //Returns the lowest integer of the specified object
[arr removeObjectAtIndex:obj];  //removes the object from the array
NSLog(@"%@",arr);
jacob
  • 3,507
  • 2
  • 21
  • 26