Lefora Free Forum
login join
Loading
806 views

NSMutableArray - Add objects without duplicates

Page 1
1–3
rookie - member
7 posts

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];
            }

novice - member
27 posts



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];
}

?
288 posts



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 $

__________________
Page 1
1–3

Locked Topic


You must be a member to post in this forum

Join Now!