2011-12-10 73 views
0

可能重複:
How to sort an NSMutableArray with custom objects in it?排序一個的NSMutableArray由對象值

我在這裏排序的NSMutableArray newsDataArray含有NewsData對象與整型屬性NewSID的。現在正在工作。但我怎麼能以更好的方式做到這一點。有沒有更好的方法...

NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"newsID" ascending:NO]; 
NSArray *tempArray = [newsDataArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDesc]]; 
NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:tempArray]; 
NSLog(@"sortedArray=%@" ,sortedArray); 

當我使用下面的方法阻止一些錯誤顯示。我想排序newsDataArray作爲我最後的結果....誰能給我一個明顯的例子...

+0

檢查這個問題的答案,它提供了幾種方法來做到這一點:http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it –

回答

7

有幾種方法,這裏使用comparator

對於NSArray的 - >新的Array對象:

array = [array sortedArrayUsingComparator: ^(id a, id b) { 
    return [a.newsTitle compare:b.newsTitle] 
} 

對於的NSMutableArray - >代替:

[array sortUsingComparator: ^(id a, id b) { 
    return [a.newsTitle compare:b.newsTitle] 
}]; 

排序由標量:

[array sortUsingComparator: ^(id a, id b) { 
    if (a.newsID < b.newsID) { 
     return (NSComparisonResult)NSOrderedAscending; 
    } else if (a.newsID > b.newsID) { 
     return (NSComparisonResult)NSOrderedDescending; 
    } 
    return (NSComparisonResult)NSOrderedSame; 
}]; 
+0

想比較'newsID'是一個int值...我怎麼能... –

+0

請看我的編輯。 – vikingosegundo

+0

在這裏我將創建我的對象a和b ... –

相關問題