4
votes

Sorry for asking silly question..

I have an array with class objects like:

Class User {
     NSString *firstName, *LastName;
}
@property (nonatomic, retail) NSString *firstName;
@property (nonatomic, retail) NSString *LastName;

I am creating object of this class and adding it in NSMutableArray.

Now I want to sort this array by the first name.. Any idea please.

Can I use NSSortDescriptor for sorting this array or I have to use my custom logic.

I had done this thing earlier but now I forgot this and don't have source code for that right now...

Please help me.. Thanks

EDIT: I got few kind replies and I tried but not working. I am parsing JSON so there will be unknown number of objects in myArray. So I used :

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

and

 NSMutableArray *tempArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

but nothing worked..

Edit 2

Here is the description: Array

    "<User: 0xa3f13c0>",
    "<User: 0xa3f1410>",
    "<User: 0xa3f1450>",
    "<User: 0xa3f1490>"

Sorted Array

"<User: 0xa3f13c0>",
"<User: 0xa3f1410>",
"<User: 0xa3f1490>",
"<User: 0xa3f1450>"

In for Loop: Array

John
abc
test
qwertg

Sorted Array

John
abc
test
qwertg
2
Could you post the NSLog output of both arrays pre and post sorting? I'd add a description override in the User class before doing that, should look something like -(NSString *)description { return [NSString stringWithFormat:@"Firstname - %@", self.firstName];}Zaky German

2 Answers

9
votes

If you're targeting iOS4+ then you can use sortUsingComparator: method:

[yourArray sortUsingComparator:^(id obj1, id obj2){

        User* u1 = (User*)obj1;
        User* u2 = (User*)obj2;
        return [u1.firstName compare:u2.firstName];
    }];

Edit: As compare method takes into account character case you may need to use caseInsensitiveCompare: method instead of it:

[yourArray sortUsingComparator:^(id obj1, id obj2){

        User* u1 = (User*)obj1;
        User* u2 = (User*)obj2;
        return [u1.firstName caseInsensitiveCompare:u2.firstName];
    }];
4
votes

This is probably the cleanest way to do what you're looking for:

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

A fun way to sort arrays is using code blocks, if you don't need pre ios4 backwards compatibility though

[myMutableArray sortUsingComparator:
^(id a, id b) 
{
    User *userA = (User *)a;
    User *userB = (User *)b;
    return [userA.firstName compare:userB.firstName]; 
}];

This will allow you to stick some additional logic there in case you'll want to use additional or other sorting conditions in the future.