Search code examples
iphoneiossortingnsmutablearraynssortdescriptor

How to use sortUsingFunction (or sortUsingSelector) to sort NSMutableArray of objects containing arrays


I have an NSMutableArray of model objects. Each model object contains an NSArray of NSNumbers. I want to sort the model objects based on the lowest NSNumber value from their respective number arrays.

What's the best way to implement this using sortUsingFunction (or sortUsingSelector)? I'm still supporting iOS 3.2 so I can't use blocks.

Currently, I'm tagging each model object with the lowest NSNumber value, and then using an NSSortDescriptor on the tag key... but I'm sure there's a better way...


Solution

  • I'm not sure if this is the cleanest or most efficient way to do it, but you can write a method for your model class - (NSComparisonResult)compare:(MyModel *)otherModel, which you would:

    1. Sort the NSArray of NSNumbers for both the self and otherModel objects using sortedArrayUsingSelector:@selector(compare:)
    2. Get the NSNumber object at index 0 for both of the two sorted arrays you created in step 1 (which will be the lowest value in each array)
    3. Return the result of [lowestSelfNumber compare:lowestOtherNumber]

    Then you can sort the mutable array with sortUsingSelector:@selector(compare:)