I have this problem with removing duplicate objects from an array. I tried these already:
noDuplicates = _personalHistory.personalHistory;
for (int i=[noDuplicates count]-1; i>0; i--) {
if ([noDuplicates indexOfObject: [noDuplicates objectAtIndex: i]]<i)
[noDuplicates removeObjectAtIndex: i];
}
for (PersonalHistory_artikels *e in _personalHistory.personalHistory) {
if (![noDuplicates containsObject:e]) {
NSLog(@"Dubplicates");
[noDuplicates addObject:e];
}
}
for (i=0; i<_personalHistory.personalHistory.count; i++) {
PersonalHistory_artikels *test = [_personalHistory.personalHistory objectAtIndex:i];
for (j=0; j<_personalHistory.personalHistory.count; j++) {
PersonalHistory_artikels *test2 = [_personalHistory.personalHistory objectAtIndex:j];
if (! [test.nieuwsTITLE_personal isEqual:test2.nieuwsTITLE_personal]) {
NSLog(@"Add test = %@", test.nieuwsTITLE_personal);
[noDuplicates addObject:test];
}
}
}
But none of the above gave me the right array. The last one was the best, but it still showed duplicate values. Can someone help me with this problem? Thank you very much.
Just convert the array to an NSSet
and back again. A set can't have duplicates by design.
Note that a set doesn't have a sorting order. Therefore, you can go cheaper and forgo the order, or go for a slightly more expensive operation but keep the order.
NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];
In OS X 10.7 and iOS 5.0 and later:
newArray = [[NSOrderedSet orderedSetWithArray:oldArray] array];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With