Crystal
Crystal

Reputation: 29518

sortedArrayUsingSelector on custom Classes?

I have a NSMutableArray that has custom objects in it. Each object does have a name attribute. Is there a way to use

[myArray    sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]

on the name somehow? Like

[myArray.name sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]

Or am I better off writing a sort function for my custom class to sort by name? Thanks.

Upvotes: 2

Views: 4985

Answers (3)

gcamp
gcamp

Reputation: 14672

In this case you need to use a NSSortDescriptor.

NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
NSArray* sortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

Upvotes: 11

omz
omz

Reputation: 53561

There are several ways to achieve this, one would be to define your own comparison method, as others have suggested, but if it's just a one-off thing, you could also use the new NSComparator API to use a block for sorting:

NSArray *sortedArray = [array sortedArrayUsingComparator:^(id obj1, id obj2) {
    return [[(MyClass *)obj1 name] caseInsensitiveCompare:[(MyClass *)obj2 name]];
}];

Upvotes: 4

jaminguy
jaminguy

Reputation: 25930

I think this answer is what you're looking for.

How to sort an NSMutableArray with custom objects in it?

Upvotes: 0

Related Questions