我无法删除NSArray iPhone中的重复对象 [英] i cannot remove duplicate objects in a NSArray iphone
本文介绍了我无法删除NSArray iPhone中的重复对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我现在要疯了。我有一个带有一堆Person对象的NSMutableArray。我想删除重复的对象,但无法使用。这就是我得到的:
I'm going crazy right now. I have a NSMutableArray with a bunch of Person objects. I want to remove the duplicated objects but it won't work. This is what i got:
NSMutableArray *withoutDoubles =[[NSMutableArray alloc]init];
NSArray *temp = [[NSArray alloc] initWithArray:tempResults];
for (Person *person in temp) {
if(![withoutDoubles containsObject:person]) {
[withoutDoubles addObject:person];
}
}
for (Person *person in withoutDoubles) {
NSLog(@"----> %@",person.name);
}
那是行不通的,我仍然重复。我也尝试过:
That is not working, i still got duplicates. I also tried:
NSArray *temp = [[NSArray alloc] initWithArray:tempResults];
NSSet *set = [NSSet setWithArray:temp];
但它也不起作用。我需要一些帮助。
But it didn't work either. I need some help here.
预先感谢。
推荐答案
如果您定义重复项是两个单独的Person对象,它们的属性设置相同,那么实现此目的的最佳方法是在您的Person对象中覆盖这两个方法
If your definition of a duplicate is two separate Person objects whose properties are set the same then the best way to achieve this is to override these two methods in your Person object
- (BOOL)isEqual:(id)anObject
- (NSUInteger)hash
然后您需要执行以下操作
You would then need to do the following
for (Person *personToTest in temp) {
BOOL duplicate = NO;
for (Person *person in withoutDoubles) {
if ([personToTest isEqual:person]) {
duplicate = YES;
break;
}
}
if (!duplicate) {
[withoutDoubles addObject:personToTest];
}
}
这篇关于我无法删除NSArray iPhone中的重复对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文