2012-02-08 42 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);