开发者

How do I sort a NSMutableArray by NSString length?

开发者 https://www.devze.com 2023-02-10 03:53 出处:网络
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:

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];
    }];
0

精彩评论

暂无评论...
验证码 换一张
取 消