Re: Deleting duplicates in NSMutableArray
Re: Deleting duplicates in NSMutableArray
- Subject: Re: Deleting duplicates in NSMutableArray
- From: James DiPalma <email@hidden>
- Date: Mon, 5 Jul 2004 14:27:33 -0700
Another solution to consider is using a second mutable array and
utilizing removeObject:'s ability to remove multiple objects that
compare equal (using isEqual:).
This solution would depend on a while loop (I don't like while loops,
but what is an infinite loop among friends), and will temporarily use
up memory (as would this thread's NSSet solution), but would preserve
order (using NSSet would not preserve order?).
Typing into Mail (given an array named "array" and not bothering to
declare variables):
uniqueArray = [NSMutableArray array];
while ([array count] > 0) {
object = [array objectAtIndex:0];
[uniqueArray addObject:object];
// Remove all objects isEqual: to object from array
[array removeObject:object];
}
Its conceptually pretty simple which makes me feel better when reading
this code (I would be a little nervous using a while(), but I prefer
this code over nesting for loops and changing their index variables).
-jim
On Jul 5, 2004, at 12:54 PM, Darkshadow wrote:
On Jul 5, 2004, at 12:20 AM, Johan Kool wrote:
Grmbl.... as always, that one clear moment comes right after pressing
that "Send" button...
For the archives, this should do it:
// Delete duplicates
for (i=0; i < [mutArray count]; i++ ) {
for (j=(i+1); j < [mutArray count]; j++) {
if ([[mutArray objectAtIndex:i] isEqualTo:[mutArray
objectAtIndex:j]]) {
[mutArray removeObjectAtIndex:j];
j--; // everything shifts down, so at j there is now an
entry we haven't yet checked
}
}
}
NS[Mutable]Array also has a method -containsObject: that you may be
able to use:
If you don't want duplicate objects at all, you could use that when
you're adding objects to the array so that it wouldn't add a duplicate
object.
Darkshadow (sometimes known as Mike Nickerson)
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.