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
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];
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With