首页 > 移动平台 > 详细

iOS NSMutableArray "removeObjectIdenticalTo" vs "removeObject"

时间:2015-11-19 20:49:58      阅读:474      评论:0      收藏:0      [点我收藏+]

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 均被删除。

 

iOS NSMutableArray "removeObjectIdenticalTo" vs "removeObject"

原文:http://www.cnblogs.com/davesuen/p/4978916.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!