2017-03-20 47 views
1

我有NSArrayNSDictionary。我有兩個特定的鍵我想用來排序我的數組。基本上,我現在有兩個NSSortDescriptor S:通過加權兩個參數來排序NSArray

descriptor = [NSSortDescriptor sortDescriptorWithKey:@"averageNote" ascending:NO]; 
descriptor2 = [NSSortDescriptor sortDescriptorWithKey:@"[email protected]" ascending:NO]; 

他們只是我的排序基於平均注意到其元素的數組,然後在第二位基於評論數量。

我想結合這兩個要素來做出更真實​​的排名:例如,70%的平均音和30%的評論數。

我該如何做到這一點?

+0

看看這個問題:http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it。您可以使用塊對數組進行排序,並可以將平均值和計數值乘以上述百分比並比較結果。 –

+0

太好了,非常感謝。 –

+0

完成此操作的另一種方法是添加計算屬性say'rank'並將其用於排序。 –

回答

0

這個代碼將讓您想要軍銜的數組排序本身,陣列將被升序排列,如果按降序想它,改變NSOrderedAscendingNSOrderedDescending

NSMutableArray *array = [@[] mutableCopy]; 
[array sortedArrayWithOptions:NSSortStable usingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { 
    aClass a = obj1; 
    aClass b = obj2; 
    float rankOfA = a.averageNote*0.7 + a.reviewCount*0.3; 
    float rankOfB = b.averageNote*0.7 + b.reviewCount*0.3; 
    if (rankOfA > rankOfB) { 
     return NSOrderedAscending; 
    } 
}];