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

1

1 Answer 1

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;
}];
Sign up to request clarification or add additional context in comments.

4 Comments

want to compare 'newsID' that is an int value ... how can i ...
here where i will create my objects a and b ...
its saying error ' a and b not found' ...
the method sortUsingComparator: passes the objects in to the block. If your code is not working, please check the documentation for blocks and these sorting methods.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.