I have a NSMutableArray containing NSStrings of various lengths. How would I go about sorting the array by the string length?
            Asked
            
        
        
            Active
            
        
            Viewed 4,677 times
        
    2 Answers
33
            See my answer to sorting arrays with custom objects:
NSSortDescriptor *sortDesc= [[NSSortDescriptor alloc] initWithKey:@"length" ascending:YES];
[myArray sortUsingDescriptors:@[sortDesc]];
 
    
    
        Guntis Treulands
        
- 4,764
- 2
- 50
- 72
 
    
    
        Georg Schölly
        
- 124,188
- 49
- 220
- 267
5
            
            
        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];
    }];
 
    
    
        Kudit
        
- 4,212
- 2
- 26
- 32
 
    