简体   繁体   中英

How can one sort an NSMutableArray of NSMutableArrays containing NSStrings?

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.

如果您的NSMutableArray仅包含NSString类型的对象,则只需执行以下操作:

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

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

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]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM