2012-11-13 94 views
2

即時通訊的問題是,我不能排序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]; 

有任何疑問,請不要向下票,就問我,我會編輯的問題。

最好的問候和抱歉,我可憐的英語。

回答

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]; 
}]; 
+0

由於它的工作:)已經一個側面說明可以在被NSOrderedAscending排序?是的,如何? –

+0

@BrunoVasconcelos是的,只是將「rating1 compare:rating2」與「rating2 compare:rating1」相反。 – trojanfoe

+0

天才:P謝謝! –