我遇到的问题是我无法排序NSMutableArray的NSMutableDictionary对象,我想通过评级对对象进行排序,评级是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];
有任何疑问,请不要投票,只要问,我会编辑问题。
最好的问候,对不起我的英语不好。
答案 0 :(得分:4)
这应该做你想要的:
NSArray *sortedArray = [arrayMealRating sortedArrayUsingComparator:^(id obj1, id obj2) {
NSNumber *rating1 = [(NSDictionary *)obj1 objectForKey:@"setMealRating"];
NSNumber *rating2 = [(NSDictionary *)obj2 objectForKey:@"setMealRating"];
return [rating1 compare:rating2];
}];