i cannot remove duplicate objects in a NSArray iphone
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 contain开发者_开发百科sObject: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.
Thanks in advance.
You can have problem with isEquals: method. Two objects are equals, when both have same hash. isEquals: documentation
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
which will allow you to properly achieve the compare.
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];
}
}
Are you sure that persons with the same name are really the same object (i.e. the pointer is pointing to the same address)?
what is person ? any custom object ??? if so then add any unique ID in that class and then compare with that ID.
Try this one, i hope this may help you
NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
[mutableArray removeObjectAtIndex:index];
}
index--;
}
[copy release];
Well you could just do it like this:
NSMutableArray*array1 = [NSMutableArray arrayWithObjects:person,person1,person2,nil];
NSMutableArray*array2 = [NSMutableArray arrayWithObjects:person1,person2,person,nil];
for (Person*person in array1)
{
if ([array2 containsObject:person])
{
[array2 removeObject:person];
}
}
This will remove all duplicates found in array2
. You can also use isEqual:
to compare the objects, that's up to you. Replace array1
and array2
with your two arrays and give it a go.
One liner: uniqueArray = [[NSSet setWithArray:temp] allObjects];
精彩评论