views:

352

answers:

2

I am just looking at sorting an NSArray of NSNumbers into numeric order but am a little unsure of the best way to go. By my way of thinking 001 and 002 are pretty comparable, so I would suspect either will do. For 003 I am not sure if returning NSMutableArray when the method expects NSArray is good practice, it works, but it feels awkward.

-(NSArray *)testMethod:(NSArray *)arrayNumbers {    
    // 001
    NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:arrayNumbers];
    [sortedArray sortUsingSelector:@selector(compare:)];
    arrayNumbers = [NSArray arrayWithArray:sortedArray];
    return(arrayNumbers);   
}

.

-(NSArray *)testMethod:(NSArray *)arrayNumbers {    
    // 002
    NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:arrayNumbers];
    [sortedArray sortUsingSelector:@selector(compare:)];
    arrayNumbers = [[sortedArray copy] autorelease];
    return(arrayNumbers);   
}

.

-(NSArray *)testMethod:(NSArray *)arrayNumbers {    
    // 003
    NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:arrayNumbers];
    [sortedArray sortUsingSelector:@selector(compare:)];
    return(sortedArray);    
}

gary

+2  A: 

I think you can just call

return [arrayNumbers sortedArrayUsingSelector:@selector(compare:)];
zonble
Thank you, zondle.
fuzzygoat
+6  A: 

You don't need a mutable array at all. You can just do:

NSArray* sortedArray = [arrayNumbers sortedArrayUsingSelector:@selector(compare:)];
Jason Coco
Thank you Jason, totally missed that one, much appreciated.
fuzzygoat