2011-06-30 41 views
0

我面臨排序問題。該場景解釋爲:我有一個類(假設的人),它有4個屬性(firstName,lastName,Address,salary),我創建了它的對象並創建了一個所有屬性的集合,並將這個對象放在一個NSMutableArray中,等等。所以在數組的每一個索引中,我都有一個對象(即4個屬性的集合)。現在我想根據薪水對這個數組進行排序,任何人都可以幫我解決這個問題,會很感激。,排序自定義類對象的數組

+0

標題很混亂,我認爲這是關於類的數組。 – 2011-06-30 06:53:29

回答

0

請參閱NSArray的文檔。它有幾種排序方法。搜索單詞「排序」,你會發現他們。 (你會想要基於塊或功能的API)。

0

使用本

NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:@"salary" ascending:YES] autorelease]; 
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter]; 
    [yorArrary sortUsingDescriptors:sortDescriptors]; 
+0

@Ishu,Maulik: 我已經實現了這樣的,但我的程序給我的例外「線程1:程序接收到的信號:SIGABRT」並墜毀 NSSortDescriptor *分揀= [[[NSSortDescriptor頁頭​​] initWithKey:@「工資「升序:YES] autorelease]; NSArray * sortDescriptors = [NSArray arrayWithObject:sorter]; [appDelegate.ContactArray sortUsingDescriptors:sortDescriptors]; 關於此行爲的任何想法? –

+0

給日誌消息顯示你得到的任何異常。 – Ishu

+0

Ishu其實我不確切知道錯誤是什麼,在何時到達這一行 [appDelegate.ContactArray sortUsingDescriptors:sortDescriptors]; 程序崩潰,只是接收到這條日誌消息「拋出'NSException'的實例後終止調用」 –

0

要麼你實現你的對象比較法:

- (NSComparisonResult)compare:(Person *)otherObject { 
return [self.birthDate compare:otherObject.birthDate]; 
} 

NSArray *sortedArray; 
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)]; 

或者平時甚至更好:(NSSortDescriptor的默認排序選擇是比較:)

NSSortDescriptor *sortDescriptor; 
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate" 
              ascending:YES] autorelease]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
NSArray *sortedArray; 
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];