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 匹配字符串或地址。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您使用的是
removeObject
,它会删除与您传入的对象“相等”的所有对象。根据 此 Apple 文档:您将看到效果文字字符串,其中每个
@"hi"
对象将成为刚刚添加多次的同一个对象。你真正想做的是:
然后你专门删除索引 2 处的对象。
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: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:
Then you're specifically removing the object at index 2.
根据 https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html
这正是您所看到的行为。如果要删除特定位置的对象,则需要
removeObjectAtIndex:
。According to https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html
which is exactly the behaviour you're seeing. If you want to remove the object at a particular position, you want
removeObjectAtIndex:
.