How can one sort an NSMutableArray of NSMutableArrays containing NSStrings?

不想你离开。 提交于 2019-12-14 01:48:26

问题


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.


回答1:


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



回答2:


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

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



回答3:


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.




回答4:


You can sort by key with:

NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"key" ascending:NO];
[yourArray sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];


来源:https://stackoverflow.com/questions/1103317/how-can-one-sort-an-nsmutablearray-of-nsmutablearrays-containing-nsstrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!