1

I have a NSArray i want to sort by longest string to shortest string

For example-

 NSArray *strings=[NSArray arrayWithObjects:@"as12332", @"ol", @"st", @"br", @"gj", @"wr", @"qwos", nil];

i want result like-

@"as12332",@"qwos", @"ol", @"st", @"br", @"gj", @"wr".

sort by string length.

user4261201
  • 2,324
  • 19
  • 26
janmejay
  • 35
  • 6
  • 1
    possible duplicate of [How to sort an NSMutableArray with custom objects in it?](http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it) – Ilya O. Aug 26 '15 at 11:43

1 Answers1

0

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.

Rony Rozen
  • 3,957
  • 4
  • 24
  • 46