2012-02-09 95 views
3

當執行此代碼:排序NSOrderedSet使用NSSortDescriptor

NSSortDescriptor *sortDescriptor = [Characteristic sortDescriptor]; 
[workingSet sortUsingComparator:[sortDescriptor comparator]]; 

我得到這個錯誤:

*** -[NSMutableOrderedSet sortUsingComparator:]: comparator cannot be nil 

sortDescriptor是非零,所以我不知道爲什麼這是行不通的。

我可以解決與下面的代碼,它完美的作品的問題:

NSSortDescriptor *sortDescriptor = [Characteristic sortDescriptor]; 
NSArray *workingArray = [[workingSet array] sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 
workingSet = [NSMutableOrderedSet orderedSetWithArray:workingArray]; 

回答

8

檢查出這兩種方法

對於第一種方法的典型用法之間的差別NSArray提法是這樣的

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) { 

    if ([obj1 integerValue] > [obj2 integerValue]) { 
     return (NSComparisonResult)NSOrderedDescending; 
    } 

    if ([obj1 integerValue] < [obj2 integerValue]) { 
     return (NSComparisonResult)NSOrderedAscending; 
    } 
    return (NSComparisonResult)NSOrderedSame; 
}]; 

(來自實施例Apple

凡爲第二種方法會更喜歡:

NSSortDescriptor *nameSort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:nameSort]; 

NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors]; 
+0

那麼,爲什麼不NSSortDescriptor的'-comparator'方法生產出符合'-sortedArrayUsingComparator工作的比較:'或'-sortUsingComparator:'? – paulmelnikow 2012-02-11 19:22:20

+2

儘管你的sortDescriptor是'!= nil',我猜測'-comparator'返回'nil'。從文檔中不太清楚,但它看起來像只返回一個比較器,如果您創建了一個例如一個比較器的描述符。使用'sortDescriptorWithKey:升序:比較器:'。 – 2012-02-12 11:42:31

+0

呃。這就說得通了。但是,呃。 – paulmelnikow 2012-02-14 04:38:56

相關問題