3

I have a multi item array in Objective C where every item is a sub-array with 4 items.I need to sort the main array based on one of the values of the sub-array.

How can I do that (quickly)?

Array looks like this:

    (
    Marly,
    "Avenida Caracas - Calle 51",
    "4.637467,-74.066799",
    a,
    "10070.563466"
),
    (
    "Calle 76",
    "Avenida Caracas - Calle 76",
    "4.662918,-74.061198",
    a,
    "7250.832506"
),
    (
    Profamilia,
    "Avenida Caracas - Calle 34",
    "4.621341,-74.06976",
    a,
    "11853.104432"
),
    (
    "Avenida 39",
    "Avenida Caracas - Calle 39",
    "4.626816,-74.068687",
    a,
    "11243.556349"
)
2
  • Can you provide more information about the type of this array? Is it an NSArray of NSArrays? Commented Mar 28, 2011 at 1:18
  • Its an NSMutableArray of NSMutableArrays Commented Mar 28, 2011 at 1:20

2 Answers 2

3

You can use any number of the NSArray or NSMutableArray sorting methods. If you're on iOS 4.0 or later, the most straightforward is probably the "UsingComparator:" version. That would go something like this:

[array sortUsingComparator:^NSComparisonResult(id a, id b) {
    NSString *name1 = [a objectAtIndex:0];
    NSString *name2 = [b objectAtIndex:0];
    return [name1 localizedCaseInsensitiveCompare:name2];
}]
Sign up to request clarification or add additional context in comments.

Comments

0

nice code Anomie! exactly what i was looking for :)

but 2 things:

1 - it's "sortedArrayUsingComparator" the function for an NSArray not "sortUsingComparator"

2 - can you explain a bit the code:

^NSComparisonResult(id a, id b) {...}

like: what does the ^ does? from what i read from Apple Doc I assume what you did there was write a function to compare (the code between curly braces) and then typedef it to NSComparisonResult. but how come the objects (id a, id b) are assumed/used? is there a common way to do this for every function/data type?

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.