user393273
user393273

Reputation: 1438

NSMutableArray - Remove duplicates

i tried doing this: Values = [[NSSet setWithArray:Values] allObjects]; and no sucess,

Thanks

Upvotes: 24

Views: 21431

Answers (4)

Varun
Varun

Reputation: 597

We can use Key Value Coding:

uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.fieldNameTobeFiltered"];

Please refer the below article for complete understanding

KVC Collection Parameters

Upvotes: 1

kapil
kapil

Reputation: 671

NSMutableArray* myArray =
[[NSMutableArray alloc]initWithObjects:
@"red",@"blue",@"red",@"green",@"yellow", @"33", @"33",@"red", @"123", @"123",nil];

NSOrderedSet *mySet = [[NSOrderedSet alloc] initWithArray:myArray];
myArray = [[NSMutableArray alloc] initWithArray:[mySet array]];

NSLog(@"%@",myArray);

Upvotes: 21

Saa
Saa

Reputation: 1615

Note that the NSSet method may remove any order you have in your NSArray. You might want to loop thru your array to keep the order. Something like this:

NSMutableArray* uniqueValues = [[NSMutableArray alloc] init]; 
for(id e in Values)
{
    if(![uniqueValues containsObject:e])
    {
        [uniqueValues addObject:e];
    }
}

Upvotes: 23

kennytm
kennytm

Reputation: 523184

Your method should work, except it returns an NSArray instead of NSMutableArray. You could use

[values setArray:[[NSSet setWithArray:values] allObjects]];

to set values to the content of the new array.

Upvotes: 46

Related Questions