How do I sort a NSMutableArray by NSString length?
I have a NSMutableArray containing NSStrings of various lengths. How would开发者_如何学JAVA I go about sorting the array by the string length?
See my answer to sorting arrays with custom objects:
NSSortDescriptor *sortDesc= [[NSSortDescriptor alloc] initWithKey:@"length" ascending:YES];
[myArray sortUsingDescriptors:@[sortDesc]];
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];
}];
精彩评论