Sandeep
Sandeep

Reputation: 7334

What is the difference between NSSortDescriptor and SortedArrayUsingSelector

I am trying to sort array of strings by length. NSSortDescriptor worked but not SortedArrayUsingSelector.

Why is it?

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

[inputArray sortUsingDescriptors:@[sortDescriptor]];

and

[inputArray sortedArrayUsingSelector:@selector(length)];

Upvotes: 1

Views: 165

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726919

The call of sortedArrayUsingSelector: method returns a sorted array, leaving the original array unchanged. On the other hand, sortUsingDescriptors: sorts a mutable array in place.

Another problem is that length returns a primitive, while the selector used for sorting is expected to return a comparison result:

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

you would get the results that you expect. You can also sort in place using sortArrayUsingSelector:

[inputArray sortUsingSelector:@selector(compareLength:)];

Upvotes: 1

Related Questions