2

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

Seerex
  • 591
  • 1
  • 9
  • 21
  • Check out http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it – Keith OYS Jun 04 '14 at 04:51

2 Answers2

10

You can use the method sortedArrayUsingComparator:

NSArray *sortedArray = [anArray sortedArrayUsingComparator:^(MyClass *a, MyClass *b) {
    return [a.name caseInsensitiveCompare:b.name];
}];
sch
  • 27,436
  • 3
  • 68
  • 83
  • That worked great, thanks chap. What exactly does this do? or i don't have to worry about it? it's taking a block as an argument, right? – Seerex Mar 24 '12 at 16:29
  • Yes, it is using a block to sort the array. – sch Mar 24 '12 at 16:31
1

You can sortedArrayUsingComparator:(NSComparator)cmptr (NSArray reference) to sort the array. For instance, if you want to sort by the name property, do the following (assuming your class is called Person):

NSArray *sortedArray = [anArray sortedArrayUsingComparator:^(id a, id b) {
    NSString *first = [(Person *)a name];
    NSString *second = [(Person *)b name];
    return [first caseInsensitiveCompare:second];
}];
goetz
  • 916
  • 6
  • 14