Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Array in assending order..?

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
like image 837
Kapil Choubisa Avatar asked Dec 12 '22 13:12

Kapil Choubisa


1 Answers

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];
    }];
like image 101
Vladimir Avatar answered Dec 28 '22 06:12

Vladimir