NSMutableArray - Add objects without duplicates
I tried to add objects to a NSMutableArray while avoiding duplicates. It doesn't work! What did I wrong? Is there an more elegant way to do this?
NSMutableArray *array;
array = [NSMutableArray new];
NSString *MyResult = "thisValueChanges";
Boolean FoundIt = FALSE;
int x;
for (x = 0; x < [array count]; x++)
{
if ([array objectAtIndex:x] == MyResult)
{
FoundIt = TRUE;
}
}
if (FoundIt == FALSE)
{
[array addObject: MyResult];
}
first off, your for loop will never be implemented. Because the count is zero, as you have yet added anything to it.
Try this
NSMutableArray *array = [NSMutableArray array];
add some objects to array here
NSString *myResult = "thisValueChanges";
BOOL found = NO;
for (x = 0; x < [array count]; x++) {
if ([[array objectAtIndex:x] isEqualToString: myResult) {
found = TRUE;
break;
}
}
if (!found) {
[array addObject: MyResult];
}
Here's another possibility that uses a dictionary to eliminate duplicates (without searching). It's a command-line program:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int i ;
NSString* s ;
NSMutableDictionary* pDict =
[NSMutableDictionar dictionaryWithCapacity:argc];
for ( i = 0 ; i < argc ; i++ ) {
const char* arg = argv[i] ;
s = [NSString stringWithUTF8String:arg];
[pDict setValue:s forKey:s];
}
NSArray* pArray = [pDict allKeys] ;
NSLog(@"Unique keys");
for ( s in pArray ) {
NSLog(@"arg = %@",s) ;
}
[pool drain];
return 0;
}
716 ArgFilter/build/Debug $ ArgFilter donald duck is a duck called donald
2010-09-08 14:55:29.704 ArgFilter[17009:903] Unique keys
2010-09-08 14:55:29.706 ArgFilter[17009:903] arg = donald
2010-09-08 14:55:29.707 ArgFilter[17009:903] arg = is
2010-09-08 14:55:29.707 ArgFilter[17009:903] arg = called
2010-09-08 14:55:29.707 ArgFilter[17009:903] arg = ArgFilter
2010-09-08 14:55:29.708 ArgFilter[17009:903] arg = duck
2010-09-08 14:55:29.708 ArgFilter[17009:903] arg = a
717 ArgFilter/build/Debug $