Objective c NSSortDescriptor和SortDarRayUsingSelector之间的区别是什么

Objective c NSSortDescriptor和SortDarRayUsingSelector之间的区别是什么,objective-c,arrays,sorting,Objective C,Arrays,Sorting,我正在尝试按长度对字符串数组排序。NSSortDescriptor工作,但未使用选择器进行分拣 为什么 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO]; [inputArray sortUsingDescriptors:@[sortDescriptor]]; 及 调用sortedArrayUsingSelector:方法返回一个已排序的数组,保持原

我正在尝试按长度对字符串数组排序。NSSortDescriptor工作,但未使用选择器进行分拣

为什么

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO];

[inputArray sortUsingDescriptors:@[sortDescriptor]];


调用
sortedArrayUsingSelector:
方法返回一个已排序的数组,保持原始数组不变。另一方面,
排序描述符:
将可变数组排序到位

另一个问题是
length
返回原语,而用于排序的选择器预期将返回比较结果:

@interface NSString(MyAdditions)
-(NSComparisonResult)compareLength:(NSString*)other;
@end

@implementation NSString(MyAdditions)
-(NSComparisonResult)compareLength:(NSString*)other {
    NSInteger a = self.length;
    NSInteger b = other.length;
    if (a==b) return NSOrderedSame;
    return a<b ? NSOrderedAscending : NSOrderedDescending;
}
@end
...
NSArray *sorted = [inputArray sortedArrayUsingSelector:@selector(compareLength:)];

嗯,一个是对象类,另一个是函数名。它不起作用NSMutableArray*inputArray=[@[@[@“hello”、@“test”、@“come”、@“comehellotest”]mutableCopy];NSArray*s=[输入阵列排序使用选择器:@选择器(长度)];输出是(comehellotest,come,test,hello)@Sandeep你是对的,不是这样。我尝试了从中得到的解决方案,但也不起作用。我知道发生了什么-请查看更新。谢谢@dasblinkenlight
@interface NSString(MyAdditions)
-(NSComparisonResult)compareLength:(NSString*)other;
@end

@implementation NSString(MyAdditions)
-(NSComparisonResult)compareLength:(NSString*)other {
    NSInteger a = self.length;
    NSInteger b = other.length;
    if (a==b) return NSOrderedSame;
    return a<b ? NSOrderedAscending : NSOrderedDescending;
}
@end
...
NSArray *sorted = [inputArray sortedArrayUsingSelector:@selector(compareLength:)];
[inputArray sortUsingSelector:@selector(compareLength:)];