You can use this code to implement what you're trying to achieve:
NSArray *strings=[NSArray arrayWithObjects:@"as12332", @"ol", @"st", @"br", @"gj", @"wr", @"qwos", nil];
NSArray *sortedArray;
sortedArray = [strings sortedArrayUsingComparator:^NSComparisonResult(NSString *first, NSString *second)
{
return [self compareLengthOf:first withLengthOf:second];
}];
sortedArray will contain the elements, sorted by length.
The implementation for the comparison method is:
- (NSComparisonResult)compareLengthOf:(NSString *)firstStr withLengthOf:(NSString *)secondStr
{
if ([firstStr length] > [secondStr length])
return NSOrderedAscending;
else if ([firstStr length] < [secondStr length])
return NSOrderedDescending;
else
return NSOrderedSame;
}
You can add more logic to the comparisson method, if you would like to have a secondary sort based on alphabetical order, for example.