I have a NSMutableArray containing NSStrings of various lengths. How would I go about sorting the array by the string length?
Asked
Active
Viewed 4,653 times
2 Answers
33
See my answer to sorting arrays with custom objects:
NSSortDescriptor *sortDesc= [[NSSortDescriptor alloc] initWithKey:@"length" ascending:YES];
[myArray sortUsingDescriptors:@[sortDesc]];
Guntis Treulands
- 4,742
- 2
- 47
- 71
Georg Schölly
- 120,563
- 48
- 208
- 262
5
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];
}];
Gujamin
- 4,154
- 2
- 24
- 31