Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I would like to sort an array of custom objects based on the name(NSString) variable. The name variable can have numbers in the end.

Unsorted data: Tank 1, Tank 2, Tank 10, Tank 32, Tank 3, Tank 11

I used the following sort descriptor,

[NSSortDescriptor sortDescriptorWithKey:@"objectName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]

The resultant array gives: Tank 1, Tank 10, Tank 11, Tank 2, Tank 3, Tank32

But I need to get the array based on the actual numbers also, I mean the resultant array should be: Tank 1, Tank 2, Tank 3, Tank 10, Tank 11, Tank 32.

What change needs to be made to the sort descriptor to accomplish this?. Could someone help me on this.

share|improve this question

marked as duplicate by dasblinkenlight, H2CO3, Martin R, Marcus Adams, rmaddy Jun 17 '13 at 20:00

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

You might want to look at the sortedArrayUsingComparator: method if NSArray. You provide a block used to compare and sort the items in your array. In your case you might extract the number at the end of each string and compare those.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.