iOS根据字符串长度排序

按内容从长到短

1
2
3
4
5
6
7
8

NSArray* array = @[@"a",@"ab",@"abc",@"abcd",@"abcdefg",@"de",@"cdef",@"def",@"ab",@"abc",];
NSArray* array1 = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSUInteger len0 = [(NSString *)obj1 length];
NSUInteger len1 = [(NSString *)obj2 length];
return len0 > len1 ? NSOrderedAscending : NSOrderedDescending;
}];
NSLog(@" 原数组:%@\n新数组:%@", array, array1);

按内容从短到长

1
2
3
4
5
6
7
NSArray* array2 = @[@"a",@"ab",@"abc",@"abcd",@"abcdefg",@"de",@"cdef",@"def",@"ab",@"abc",];
NSArray* array3 = [array2 sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSUInteger len0 = [(NSString *)obj1 length];
NSUInteger len1 = [(NSString *)obj2 length];
return len0 < len1 ? NSOrderedAscending : NSOrderedDescending;
}];
NSLog(@" 原数组:%@\n新数组:%@", array2, array3);