OStack程序员社区-中国程序员成长平台

标题: iphone - 对字典对象数组进行排序 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 23:42
标题: iphone - 对字典对象数组进行排序

我遇到的问题是我无法对 NSMutableDictionary 对象的 NSMutableArray 进行排序,我想按评级对对象进行排序,评级是 NSNumber,我缺少什么?

我当前的代码对“arrayMealRating”中的所有评分求和并对结果数组进行排序:

            [arrayMealRating addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        [eachObject objectForKey"Airline"], @"Airline"
                                        ,[eachObject objectForKey"setMealRating"], @"setMealRating"
                                        , nil]];

        }
        NSArray *airlineNames = [arrayMealRating valueForKeyPath"@distinctUnionOfObjects.Airline"];

        // Loop through all the airlines
        for (NSString *airline in airlineNames) {

            // Get an array of all the dictionaries for the current airline
            NSPredicate *predicate = [NSPredicate predicateWithFormat"(Airline == %@)", airline];
            NSArray *airlineMealRating = [arrayMealRating filteredArrayUsingPredicate:predicate];

            // Get the sum of all the ratings using KVC @sum collection operator
            NSNumber *rating = [airlineMealRating valueForKeyPath"@sum.setMealRating"];

            //NSLog(@"%@: %@", airline, rating);
            [sortedMealArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        airline, @"Airline"
                                        ,[rating stringValue], @"setMealRating"
                                      , nil]];
        }



        NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey"setMealRating"  ascending:YES];
        [sortedMealArray sortedArrayUsingDescriptors:[NSMutableArray arrayWithObjects:descriptor,nil]];
        auxMealRating = [sortedMealArray copy];

如有任何疑问,请不要投反对票,只要问,我会编辑问题。

最好的问候和对不起我糟糕的英语。



Best Answer-推荐答案


这应该做你想做的:

NSArray *sortedArray = [arrayMealRating sortedArrayUsingComparator:^(id obj1, id obj2) {
    NSNumber *rating1 = [(NSDictionary *)obj1 objectForKey"setMealRating"];
    NSNumber *rating2 = [(NSDictionary *)obj2 objectForKey"setMealRating"];
    return [rating1 compare:rating2];
}];

关于iphone - 对字典对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13360709/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4