views:

163

answers:

3

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 ?)

+2  A: 

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
Jacob Relkin
+3  A: 

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]];
TechZen
thansk. it worked
mrugen
+2  A: 

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.

Joshua Nozzi