NSMutableArray - Remove duplicates

杀马特。学长 韩版系。学妹 提交于 2019-12-02 23:50:16
kennytm

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.

Sander

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

We can use Key Value Coding:

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

Please refer the below article for complete understanding

KVC Collection Parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!