sorting mutable array in alphabetical order

荒凉一梦 提交于 2019-12-09 23:12:55

问题


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


回答1:


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]];



回答2:


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



回答3:


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.




回答4:


myArray=[myDict keysSortedByValueUsingSelector:@selector(compare:)]; 

Simply Worked for me!



来源:https://stackoverflow.com/questions/3720073/sorting-mutable-array-in-alphabetical-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!