2011-03-15 23 views
9

使用NSSortDescriptor定製比較我想使用一個sortdescriptor與自定義比較器問題經由選擇器

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] 
    initWithKey:@"object.dateTime" 
    ascending:YES 
    selector:@selector(compareObject:toObject:)]; 

(關鍵是一個ManagedObject)

比較方法:

- (NSComparisonResult)compareObject:(id)date1 toObject:(id)date2 { 
    NSComparisonResult comparisonResult; 
    // Complex comparator contents 
    return comparisonResult; 
} 

然而,我得到一個錯誤: 'NSInvalidArgumentException',原因:' - [__ NSDate compareObject:toObject:]:無法識別的選擇器發送.....

我在做什麼錯? 如果我在一個塊中使用它,比較器就會工作,但我需要它通過一個選擇器來工作。 我找不到任何示例代碼或有關如何通過選擇器使用比較器的明確文檔(適用於iOS 3.x.x)。該文件談到了與自我比較,但我試圖將比較方法合併到對象中,但這也不起作用。

誰可以指出我的問題或某些示例代碼,以瞭解如何通過選擇器使用它?

注:比較器本身不是簡單的日期比較。那裏還有很多事情要做。

回答

9

如果您比較NSDate對象,則您傳遞的選擇器必須是NSDate類的方法,並且只接受一個參數。

從NSSortDescriptor DOC:

The selector must specify a method implemented by the value of the property identified by keyPath. The selector used for the comparison is passed a single parameter.

要提供自己的排序選擇,你應該上的NSDate定義類別,並在這裏把你的自定義排序方法類似

- (NSComparisonResult)customCompare:(id)toDate { 
    NSComparisonResult comparisonResult; 
    // Complex comparator contents 
    return comparisonResult; 
} 

OR如果你不不關心iOS版本< 4.0,你也可以使用

- (id)initWithKey:(NSString *)key ascending:(BOOL)ascending comparator:(NSComparator)cmptr 

cmptr是這樣的塊:

^(id date1, id date2) { 
    NSComparisonResult comparisonResult; 
    // Complex comparator contents 
    return comparisonResult; 
} 
+0

感謝。我有這個工作。 – P5ycH0 2011-03-15 09:38:50