How can I sort an NSMutableArray from an NSMutableArrays containing NSStrings?

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

I am sure there should be an easy way for this, but I cannot find it.

To clarify, I want to sort the first array alphabetically using NSString at index 3 of the subarray.

+3
source share
4 answers

I haven’t seen anyone really answer this question other than β€œuse this function, find out.” So here is some actual code that you can use.

.h( .h, )

@interface NSString (SortCompare)

-(NSInteger)stringCompare:(NSString *)str2;

@end

.m( .m .h)

@implementation NSString (SortCompare)

-(NSInteger) stringCompare:(NSString *)str2
{
    return [(NSString *)self localizedCaseInsensitiveCompare:str2];
}

@end

, sortUsingSelector:
NSMutableArray:

[myArray sortUsingSelector:@selector(stringCompare:)];

NSArray:

[myArray sortedArrayUsingSelector:@selector(stringCompare:)];
+3

NSMutableArray NSString, :

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

, NSArray compare:, , . NSArray compare:(NSArray *)otherArray ( -, , ), sortUsingSelector:.

, . .

+2
source

You can sort by key with:

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

Source: https://habr.com/ru/post/1712187/


All Articles