按对象值排序NSMutableArray

时间:2011-12-10 18:29:00

标签: objective-c ios cocoa-touch

  

可能重复:
  How to sort an NSMutableArray with custom objects in it?

这里我正在使用int属性 newsID 对包含 NewsData 对象的NSMutableArray newsDataArray 进行排序。现在正在运作。但是我怎么能以更好的方式做到这一点。有没有更好的方法......

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

当我使用以下方法时,阻止显示一些错误。我希望将newsDataArray排序为我的最终结果......任何人都给我一个明确的例子......

1 个答案:

答案 0 :(得分: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;
}];
相关问题