开发者

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜