我们可以一次使用排序描述符和@distinctUnionOfObjects吗?

时间:2013-08-05 11:02:41

标签: iphone ios nsmutablearray nssortdescriptor

由于我的要求,我需要对NSMutableArray进行排序,并需要在该数组中放置唯一值。

这是我的代码,但我遇到的问题是我得到两个数组:一个具有不同的值,另一个没有明确的值但是已经排序。

/ *Making the years unique so that it will display only once*/
        mSortingArray = [mYearsArray valueForKeyPath:@"@distinctUnionOfObjects.self"] ;
        NSLog(@"mSortingArray%@",mSortingArray);

        /*Sorting the array to get the years in assending format*/
        NSSortDescriptor *sortDescriptor;
        sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"self"ascending:YES];
        NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
        [mYearsArray sortUsingDescriptors:sortDescriptors];
        NSLog(@"%@ :%@",mYearsArray,sortDescriptors);

如何在一个数组中获得两个结果?

1 个答案:

答案 0 :(得分:7)

您无法在单个操作中执行此操作,但可以将排序描述符应用于单向操作的结果:

 NSArray *uniqueArray = [mYearsArray valueForKeyPath:@"@distinctUnionOfObjects.self"];
 NSArray *sortedUniqueArray = [uniqueArray sortedArrayUsingDescriptors:sortDescriptors];
 mYearsArray = [sortedUniqueArray mutableCopy];