Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array with custom objects

I'm trying to sort an array, filled with objects from a class i wrote. The class i wrote contains an NSString itself, as the "name". So what i wanna do, is to sort the array, based on the name property the objects contain. I tried the simple:

[anArray sortedArrayUsingSelecter: CaseInsensitiveCompare];

But as you can guess, it sends the caseInsensitiveCompare message to the objects itself, and it won't respond to that one.

So i'm guessing i have to make my objects able to respond to the caseInsensitiveCompare? Not quite sure how to write such a method, so any pointers would be lovely.

Thanks

like image 462
Seerex Avatar asked Mar 14 '26 04:03

Seerex


1 Answers

You can use the method sortedArrayUsingComparator:

NSArray *sortedArray = [anArray sortedArrayUsingComparator:^(MyClass *a, MyClass *b) {
    return [a.name caseInsensitiveCompare:b.name];
}];
like image 70
sch Avatar answered Mar 16 '26 16:03

sch