views:

899

answers:

2

Is there an easy way to sort an NSMutableArray of NSMutableArrays containing NSStrings?

I am sure that there must be an easy method for doing this but I can't seem to find it.

To Clarify I want to sort the first array alphabetically by the NSString at index 3 of the sub array.

+2  A: 

As others have mentioned, NSArray doesn't have a compare: selector that allows it to sort itself, so you'll have to define it yourself. I would create a category on NSArray with a method called compare:(NSArray *)otherArray (or something that better describes what it does) and use that with sortUsingSelector:.

Depending on your needs you could possibly stuff all your strings into a big array when you need to sort them, and use that instead. It could be a little less code to write.

Marc Charbonneau
It would seem a little dangerous to add a generic method like compare: to NSArray via a category - much better to add a uniquely named selector, or better still, use sortUsingFunction with a comparison function.
Peter N Lewis
A: 

If your NSMutableArray only contains objects of type NSString, simply do:

[myMutableArray sortUsingSelector:@selector(compare:)];
thomax