2012-02-08 38 views
2

我正在使用一个具有相同字符串对象的NSMutableArray。NSMutableArray正在删除具有相同字符串的所有对象

下面是代码

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); 

当我尝试除去阵列的第三对象,它的移除所有对象,具有“HI”字符串。 我不明白为什么会发生。
我的疑问是删除对象时,NSMutableArray匹配字符串或地址。

回答

4

这是因为你使用removeObject其删除是“平等”到你通过在一个所有对象按this Apple documentation

这种方法使用indexOfObject:定位匹配,然后删除 他们通过使用removeObjectAtIndex :.因此,在 上确定匹配是对象对isEqual:消息的响应的基础。如果 数组不包含anObject,则该方法不起作用(尽管其 的确会招致搜索内容的开销)。

你看到的effects of literal strings这里每个那些@"hi"对象会变成是相同的对象只是增加了许多倍。

你真正想要做的是这样的:

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

然后你在专门索引2

+1

错字警告:'removeObjectAtInded'应该在末尾有一个'x' :-)。 – 2012-02-08 14:21:57

+0

有关字符串文字的其他信息,请参见:http://stackoverflow.com/a/25798/250164 – 2012-02-08 14:29:45

+0

更正:'removeObject'方法不会删除所有相同的对象。相反,它只消除它的一个事件。为了移除所有“相等”的对象,我们必须使用'removeObjectIdendicalTo'方法。 – santobedi 2017-08-04 07:26:32

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);