Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hi i am having a nsmutable array and in that nearly 50 -60 object having different names ,and can i sort this array in alphabatical order (Is it possible, How?) (is it a duplicate question ?)

share|improve this question

4 Answers

up vote 10 down vote accepted

For a simple sort like this, I like to use sort descriptors.

Suppose you have an mutable array of objects whose class has a name NSString property:

NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
share|improve this answer
 
thansk. it worked –  mrugen Sep 16 '10 at 19:02
 
This will start with "W" and not with "A". How to start with "A"? –  Jonathan Developer Aug 16 at 20:20

Absolutely, you can use sortUsingSelector: for this:

[myArray sortUsingSelector:@selector(compare:)];

If your array has custom objects, then you will need to implement a sorting method on those objects:

@implementation myCustomObject
  ...

  -(NSComparisonResult) compare:(myCustomObject*) other {
      return [self.name compare:other.name];
  }

@end
share|improve this answer
 
nice one line answer (for simple arrays). –  newenglander Jun 2 '12 at 10:48

TechZen's approach works well, but it would work better if you used NSSortDescriptor's +sortDescriptorWithKey:ascending:selector:, passing "localizedCompare:" as the selector. This way, the sorting is localized to the user's language, which can make a big difference in string comparison.

share|improve this answer
myArray=[myDict keysSortedByValueUsingSelector:@selector(compare:)]; 

Simply Worked for me!

share|improve this answer
1  
hmm .. what's the difference to earlier answers? –  kleopatra Sep 14 at 16:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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