本文介绍了按对象值对NSMutableArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我正在对NSMutableArray newsDataArray 进行排序,其中包含具有int属性 newsID NewsData 对象。现在正在工作。但是我怎样才能更好地做到这一点。有没有更好的方法...

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);

当我使用以下带有块的方法时,会显示一些错误。我想将newsDataArray排序为最终结果....任何人都给我一个清晰的示例...

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

对于NSArray->新的Array对象:

For NSArray -> new Array object:

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

对于NSMutableArray->到位:

For NSMutableArray -> in place:

[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;
}];

这篇关于按对象值对NSMutableArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 10:53