1

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...

1 Answer 1

2

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:)

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

1 Comment

Thanks, I like this solution more than my tagging method.

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.