2011-08-24 33 views

回答

6

像這樣(未經):

descriptor = [[[NSSortDescriptor alloc] 
      initWithKey:@"status" 
      ascending:YES 
      selector:@selector(customStatusCompare:)] autorelease]; 

@interface NSNumber (CustomStatusCompare) 
- (NSComparisonResult)customStatusCompare:(NSNumber*)other; 
@end 

@implementation NSNumber (CustomStatusCompare) 
- (NSComparisonResult)customStatusCompare:(NSNumber*)other { 
    NSAssert([other isKindOfClass:[NSNumber class]], @"Must be a number"); 
    if ([self isEqual:other]) { 
    return NSOrderedSame; 
    } 
    else if (... all your custom comparison logic here ...) 
    } 
} 
+0

謝謝,沒關係,但是您是否也可以幫助您完成「您所有的自定義比較邏輯」。我是一個新手... –

+1

這是一個NSNumber,所以你需要'integerValue'來獲得一個簡單的整數。將它們與<, = and >進行比較,並根據您希望如何排序它們來返回「NSOrderedDescending」,「NSOrderedSame」或「NSOrderedAscending」。在你的情況下,如果'[self integerValue]'是1,那麼它總是'NSOrderedAscending'(因爲我們已經檢查了相等性)。如果它是0,那麼它總是'NSOrderedDescending'。如果它是2,那麼你需要檢查另一個值來確定返回哪個值。 –

+1

無法獲取描述符以在類別中調用(customStatusCompare :)。 –

2

使用自定義比較器或選擇器。 NSSortDescriptor有一些方法你應該看看。從NSSortDescriptor Class Reference

+ sortDescriptorWithKey:ascending:selector: 
– initWithKey:ascending:selector: 
+ sortDescriptorWithKey:ascending:comparator: 
– initWithKey:ascending:comparator: 

你可能會遇到的問題,如果你傳遞這些類型的排序描述符的一個核心數據讀取請求時,雖然。

+0

我們似乎有這些核心數據讀取請求的「問題」。你能詳細說明原因嗎?核心數據只是拋出一個異常。 – petehare

+1

你的排序描述符是什麼樣的?核心數據提取請求不能使用自定義選擇器或比較器。 –

+0

明白了。謝謝。我們試圖使用比較器。 – petehare