22

I have to sort an array of objects by a property of the objects that is a string. How can I do this?

0

3 Answers 3

41

you need to use

-[NSArray sortedArrayUsingSelector:]

or

-[NSMutableArray sortUsingSelector:] and pass @selector(compare:) as the parameter.

here's a link to the answer Sort NSArray of date strings or objects

Sign up to request clarification or add additional context in comments.

Comments

17

For just sorting array of strings:

sorted = [array sortedArrayUsingSelector:@selector(compare:)];

For sorting objects with key "name":

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)];
sorted = [array sortedArrayUsingDescriptors:@[sort]];

Also, instead of compare: you can use:

  • caseInsensitiveCompare:

  • localizedCaseInsensitiveCompare:

Comments

8

Here's what I ended up using - works like a charm:

[categoryArray sortedArrayWithOptions:0
               usingComparator:^NSComparisonResult(id obj1, id obj2)
{
    id<SelectableCategory> cat1 = obj1;
    id<SelectableCategory> cat2 = obj2;
    return [cat1.name compare:cat2.name options:NSCaseInsensitiveSearch];
}];

SelectableCategory is just a @protocol SelectableCategory <NSObject> defining the category with all its properties and elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.