您的位置:首页 > 移动开发 > Objective-C

iOS NSMutableArray "removeObjectIdenticalTo" vs "removeObject"

2015-11-19 20:08 579 查看
NSMutableArray 有多种可以删除元素的方法。

其中 removeObject,removeObjectIdenticalTo 这两个方法是有区别的。

[anArray removeObjectIdenticalTo:anObject];


removeObject:anObject 删除所有与 anObject “isEquals” 的元素。

removeObjectIdenticalTo:anObject 删除所有与 anObject 地址相同(同一个对象)的元素。

举个例子:

数组中包含多个 NSString,其中有两个属于不同对象的,值均为 “Hello” 的元素。

调用 removeObject 将删除所有值为 “Hello” 的元素。

调用 removeObjectIdenticalTo 只删除与其地址相同的对象。

NSString *str1 = [[NSString alloc] init];
NSString *str2 = [[NSString alloc] init];
NSString *str3 = [str1 stringByAppendingFormat:@"Hello"];
NSString *str4 = [str2 stringByAppendingFormat:@"Hello"];

NSMutableArray *muArray = [NSMutableArray arrayWithCapacity:6];
[muArray addObject:@"How are you"];
[muArray addObject:str3];
[muArray addObject:str4];
for (NSObject * object in muArray) {
NSLog(@"item:%@", object);
}

if ([str3 isEqual:str4]) {
NSLog(@"str1 isEqual str2");
}
if (str3  == str4) {
NSLog(@"str1 == str2");
}
[muArray removeObjectIdenticalTo:str3];
for (NSObject * object in muArray) {
NSLog(@"item:%@", object);
}


此例子中,只有 str3 被删除。

如果把 removeObjectIdenticalTo 换为 removeObject,str3 和 str4 均被删除。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: