比较两个 NSArray
如何比较两个 NSArray,以便删除两个数组中不存在的所有内容。
我这样尝试:
NSArray *array1 = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4", nil];
NSArray *array2 = [NSArray arrayWithObjects:@"1",@"2",@"5",@"6", nil];
NSMutableArray *myMutableArray = [NSMutableArray arrayWithArray:array1];
NSMutableArray *myMutableArrayTwo = [myMutableArray copy];
[myMutableArray removeObjectsInArray:array2];
[array1 release];
[array2 release];
NSArray *array3 = [myMutableArray copy];
[myMutableArrayTwo removeObjectsInArray:array3]; // Error here: "SIGABRT"
NSLog(@"array3:%@",myMutableArrayTwo);
但由于错误而不起作用。它说:“-[__NSArrayI removeObjectsInArray:]:无法识别的选择器发送到实例 0x4e51550”
我做错了什么?或者有更简单的方法来解决我的问题吗? 感谢您的帮助
How can I compare two NSArrays so that I can delete everything that isn't in both arrays.
I tried it like this:
NSArray *array1 = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4", nil];
NSArray *array2 = [NSArray arrayWithObjects:@"1",@"2",@"5",@"6", nil];
NSMutableArray *myMutableArray = [NSMutableArray arrayWithArray:array1];
NSMutableArray *myMutableArrayTwo = [myMutableArray copy];
[myMutableArray removeObjectsInArray:array2];
[array1 release];
[array2 release];
NSArray *array3 = [myMutableArray copy];
[myMutableArrayTwo removeObjectsInArray:array3]; // Error here: "SIGABRT"
NSLog(@"array3:%@",myMutableArrayTwo);
But it doesn't work because of the error. It sais: "-[__NSArrayI removeObjectsInArray:]: unrecognized selector sent to instance 0x4e51550"
What did I do wrong? Or are there easier ways to solve my problem?
Thanks for the help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您创建了 NSMutableArray 的副本(不可变),因此您将失去可变功能。
请改用
mutableCopy
方法。顺便说一句,你有很大的记忆问题。您的
array1
和array2
变量是自动释放的对象。释放它们会给你带来问题。您只需释放使用
alloc
、copy
或mutableCopy
创建的数组即可。This is because you create a copy (non-mutable) of a NSMutableArray, so you are losing the mutable capabilities.
Use the
mutableCopy
method instead.By the way, you've got huge memory problems. Your
array1
andarray2
variables are auto-released objects. Releasing them will lead you to problems.You only need to release the arrays you created with
alloc
,copy
ormutableCopy
.根据 此处,您应该使用
addObjectsFromArray
代替arrayWithArray
因为您正在填充NSMutableArray
。According to here, you should use
addObjectsFromArray
instead ofarrayWithArray
since you are populating aNSMutableArray
.试试这个
输出:
数组3:(
1、
2
)
注意:一旦创建,你就无法从 NSArray 中删除任何对象。它是不可变的。
Try this
OUTPUT:
array3:(
1,
2
)
NOTE: u cannot remove any object from NSArray once created.its immutable.