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.
Didn't see anyone actually answering this with other than "use this function, figure it out". So here is some actual code that you can use.
Put this category at the end of your .h file (or anywhere and import the .h where ever you need to sort)
@interface NSString (SortCompare)
-(NSInteger)stringCompare:(NSString *)str2;
@end
Put this in the .m file (or the .m of the .h you're importing)
@implementation NSString (SortCompare)
-(NSInteger) stringCompare:(NSString *)str2
{
return [(NSString *)self localizedCaseInsensitiveCompare:str2];
}
@end
Now use the sort by calling sortUsingSelector: on the array
NSMutableArray:
[myArray sortUsingSelector:@selector(stringCompare:)];
NSArray:
[myArray sortedArrayUsingSelector:@selector(stringCompare:)];
If your NSMutableArray
only contains objects of type NSString
, simply do:
[myMutableArray sortUsingSelector:@selector(compare:)];
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.
You can sort by key with:
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"key" ascending:NO];
[yourArray sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];