1

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 ...

Community
  • 1
  • 1
Sachu Vijay
  • 163
  • 2
  • 10
  • Check the answer to this question, which gives several means to do so: http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it – Mike Fahy Dec 10 '11 at 18:35

1 Answers1

7

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;
}];
Community
  • 1
  • 1
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178