2013-04-02 57 views
0

編輯: 正如我想的那樣,甚至沒有問題,我只是使用錯誤的值來檢查我的結果。無法使用自定義比較器對兩個屬性進行排序

我比較我的數據庫的自定義對象和排序它們的目標有點麻煩,原則上,這很容易,排序機制必須與這個自定義對象的兩個屬性由字符串表示,但也可以包含數值。

這是我正在嘗試修復的自定義比較器塊。

NSArray *sortedArray = [baseAry sortedArrayUsingComparator:^NSComparisonResult(Obj *o1, Obj *o2) { 
NSComparisonResult comp1 = [o1.attr_a compare:o2.attr_a]; 
if (comp1 == NSOrderedSame) { 
    return [o1.attr_b compare:o2.attr_b];  
} 
return [o1.attr_a compare:o2.attr_a]; 
}]; 

最後,列表應該是這樣的:

  • 12 - 3
  • 12 - 8
  • 13 - 1
  • 14 - 2
  • 14 - 4
  • 22 - 1 etc

但使用電流比較我只得到這樣一個結果:

  • 12 - 8
  • 12 - 3
  • 13 - 1
  • 14 - 4
  • 14 - 2
  • 22 - 3
  • 22 - 2
  • 22 - 1

是否有一個舒適的方式來做到這一點的代碼塊?我可以想象的另一種方法是將列表拆分爲子列表並將它們分開排序並將它們粘合在一起,但這可能需要更高的計算能力

+0

如果你正在返回相同的值什麼是如果循環檢查比較是相同的? –

+0

你的問題看起來類似於這個http://stackoverflow.com/questions/15610434/sorting-array-based-on-custom-object-values/15611004#15611004 –

+0

你也可以這樣做: NSSortDescriptor * firstSorter = [[NSSortDescriptor alloc] initWithKey:@「firstProperty」升序:YES]; NSSortDescriptor * secondSorter = [[NSSortDescriptor alloc] initWithKey:@「secondProperty」升序:YES]; NSArray * sortedArray = [array sortedArrayUsingDescriptors:@ [firstSorter,secondSorter]]; –

回答

0

您應該首先比較兩個對象的attr_a。如果它們相等,比較兩個對象的attr_b

NSComparisonResult comp = [o1.attr_a compare:o2.attr_a]; 
if (comp == NSOrderedSame) { 
    comp = [o1.attr_b compare:o2.attr_b];  
} 
return comp; 

(。您的代碼進行比較的第一個對象attr_a與第二對象,這並沒有多大意義的attr_b

+0

對不起,我剛剛在代碼中發現了一個錯誤:剛剛發佈的就是這個。這似乎並不是它。我比較attr_a,如果他們是相同的我比較attr_b和返回分別。 – fletcher

相關問題