2010-09-25 67 views
0

比方說,我有一個自定義對象的數組。自定義類看起來像這樣如何通過Cocoa Touch中的某個屬性來排列對象的數組?

Person 
------- 
name 
number 

現在讓我們說,我要重新排列這些對象的數組,這樣的對象由數量排序。如何才能做到這一點?

+1

Xcode是一個IDE,它不是一種編程語言/庫。 – kennytm 2010-09-25 10:23:40

+0

可能的重複[如何排序與自定義對象的NSMutableArray?](http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it) – 2011-02-14 12:14:09

回答

2

1)你必須實現以下在Person類方法

- (NSNumber *)numberForSorting { 
    return self.number; 
} 

- (NSComparisonResult)compare:(Person *)person { 
    return [[self numberForSorting] compare:[person numberForSorting]]; 
} 


2)當一個人數組必須是那種你剛纔所說的)的情況下,

NSMutableArray

[peopleMutableArray sortUsingSelector:@selector(compare:)]; 

b)在NSArray

NSArray *sortedPeople = [peopleArray [email protected](compare:)]; 
+1

這幾乎是正確的答案。在numberForSorting方法中,您將返回self.number的NSNumber表示形式,而不是self.name。 – 2010-09-26 08:08:43

+0

你很對,編輯 – knuku 2010-09-26 08:49:49

相關問題