Sort a NSMutableArray by Object values
Possible Duplicate:
How to sort an NSMutableArray with custom objects in it?
Here i am sorting the NSMutableArray newsDataArray containing the NewsData Objects with int property newsID. This is working now . But how can i do this in a better way . Is there any better methods ...
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"newsID" ascending:NO];
NSArray *tempArray = [newsDataArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:tempArray];
NSLog(@"sortedArray=%@" ,sortedArray);
when i am using the following methods with block some error is showing. I want sorted newsDataArray as my final result .... Anyone give me a clear example ...
There are several ways, here by using a comparator
For NSArray -> new Array object:
array = [array sortedArrayUsingComparator: ^(id a, id b) {
return [a.newsTitle compare:b.newsTitle]
}
For NSMutableArray -> in place:
[array sortUsingComparator: ^(id a, id b) {
return [a.newsTitle compare:b.newsTitle]
}];
Sorting by scalars:
[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;
}];
链接地址: http://www.djcxy.com/p/70812.html
上一篇: 如何以时间比较的升序对nsmutablearray进行排序
下一篇: 按对象值排序NSMutableArray