简体   繁体   中英

How to sort NSArray of NSStrings using NSPredicate?

I have NSarray contains the list of Animals. The array contains a list of animals with repeated elements. I have to make an array with distinct values in the array. Repeated values should be removed using NSPredicate .

Here is my Code :-

NSArray *arrAnimals = [[NSArray alloc] initWithObjects:@"Cat",@"Rat",@"Fish",@"Cat",@"Fish",@"Cat",@"Cat",@"Bird",@"Fish",@"Cat",@"Frog", nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"distinct"]];
arrAnimals = [arrAnimals filteredArrayUsingPredicate:predicate];

Here I am using "distinct" keyword for sorting the array, but not able to find any solution. I have preferred many links.

http://www.infragistics.com/community/blogs/stevez/archive/2013/10/21/ios-objective-c-filtering-a-nsarray-using-nspredicate.aspx

Please resolve my problem.

没有谓词,但是可以使用键值运算符:

distinct = [array valueForKeyPath:@"@distinctUnionOfObjects.self"];

You can remove duplicates from an array by creating a set with its objects and converting it back to an array.

NSArray *arrAnimals = [[NSArray alloc] initWithObjects:@"Cat",@"Rat",@"Fish",@"Cat",@"Fish",@"Cat",@"Cat",@"Bird",@"Fish",@"Cat",@"Frog", nil];
NSArray *arrayWithoutDuplicates = [[NSSet setWithArray:arrAnimals] allObjects];

try this one with answered by @iMartin

 NSArray *arrAnimals = @[@"Cat",@"Rat",@"Fish",@"Cat",@"Fish",@"Cat",@"Cat",@"Bird",@"Fish",@"Cat",@"Frog"];

    arrAnimals= [arrAnimals valueForKeyPath:@"@distinctUnionOfObjects.self"];

    arrAnimals= [arrAnimals sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        unichar firstChar =  [obj1 characterAtIndex:0];
        unichar secondChar =  [obj2 characterAtIndex:0];

        if ( firstChar == secondChar) {
            return NSOrderedSame;
        } else {
            if ( firstChar > secondChar) {
                return NSOrderedDescending;
            } else {
                return NSOrderedAscending;
            }

        }

    }];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM