xcode 按字母顺序对可变数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3720073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:44:50  来源:igfitidea点击:

sorting mutable array in alphabetical order

iphoneobjective-cxcodensmutablearraynsarray

提问by mrugen

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

我有一个 nsmutable 数组,其中将近 50 -60 个对象具有不同的名称,我可以按字母顺序对这个数组进行排序吗(是否可能,如何?)

回答by TechZen

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

对于像这样的简单排序,我喜欢使用排序描述符。

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

假设您有一个可变对象数组,其类具有nameNSString 属性:

NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];

回答by Jacob Relkin

Absolutely, you can use sortUsingSelector:for this:

当然,您可以使用sortUsingSelector:

[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

回答by Joshua Nozzi

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.

TechZen 的方法效果很好,但如果您使用 NSSortDescriptor 的 +sortDescriptorWithKey:ascending:selector:,将“localizedCompare:”作为选择器传递,效果会更好。通过这种方式,排序被本地化为用户的语言,这可以在字符串比较中产生很大的不同。

回答by royemi

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

Simply Worked for me!

简直对我来说有效!