Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a NSMutableArray by NSString length?

I have a NSMutableArray containing NSStrings of various lengths. How would I go about sorting the array by the string length?

like image 219
henryeverett Avatar asked Feb 14 '11 12:02

henryeverett


People also ask

How do you sort an array of strings in Objective C?

For just sorting array of strings: sorted = [array sortedArrayUsingSelector:@selector(compare:)]; For sorting objects with key "name": NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)]; sorted = [array sortedArrayUsingDescriptors:@[sort]];

How do you sort an array of objects in Objective C?

The trick to sorting an array is a method on the array itself called "sortedArrayUsingDescriptors:". The method takes an array of NSSortDescriptor objects. These descriptors allow you to describe how your data should be sorted.


2 Answers

See my answer to sorting arrays with custom objects:

NSSortDescriptor *sortDesc= [[NSSortDescriptor alloc] initWithKey:@"length" ascending:YES];

[myArray sortUsingDescriptors:@[sortDesc]];
like image 116
Georg Schölly Avatar answered Nov 10 '22 23:11

Georg Schölly


This is how I did it (love me some blocks!)

_objects = [matchingWords sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        NSNumber *alength = [NSNumber numberWithInt:((NSString*)a).length];
        NSNumber *blength = [NSNumber numberWithInt:((NSString*)b).length];
        return [alength compare:blength];
    }];
like image 32
Gujamin Avatar answered Nov 11 '22 00:11

Gujamin