如何对NSMutableArray按字母顺序进行排序?

25

我想对一个NSMutableArray对象按字母顺序进行排序。


2
数组中的对象类型是什么? - Eiko
我正在将一个对象存储在数组中,我希望按照对象名称字段对该数组进行排序。 - Ali
7个回答

103

您可以使用以下方法对NSMutableArray进行排序:

[yourArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

[tempPeoples sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 我使用了这段代码,但是它抛出了异常。 - Ali
请问您能否发布异常语句。 - Mobile Developer iOS Android
NAddressBook[5197:207] *** -[AddressData localizedCaseInsensitiveCompare:]: 无法识别的选择器发送到实例0x149160 2011-01-18 17:01:14.470 NAddressBook[5197:207] *** 终止应用程序,原因是未捕获的异常 'NSInvalidArgumentException',原因:'*** -[AddressData localizedCaseInsensitiveCompare:]:无法识别的选择器发送到实例0x149160' 2011-01-18 17:01:14.484 NAddressBook[5197:207] 堆栈:( - Ali
也许这些对象不是NSString类型的...编辑:是的 :-) - Eiko
好的,不是字符串的问题。问题在于我正在将对象存储在数组中,该对象包含一个名为“name”的字段,我想根据该字段对数组进行排序。 - Ali
我的是字符串数组。但仍然崩溃。 - Bagusflyer

48

这里提供的其他答案提到使用@selector(localizedCaseInsensitiveCompare:)。
对于NSString数组,这很有效, 但是OP评论说该数组包含对象,并且应根据对象的name属性进行排序。
在这种情况下,您应该执行以下操作:

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

您的对象将根据这些对象的名称属性进行排序。


1
这是针对这个特定问题的更好答案。非常有效! - Ricardo RendonCepeda
哈哈!10年后仍是一个很好的答案!Cocoa和Objective-C万岁! - Neville Nason

1
在最简单的情况下,如果您有一个字符串数组:
NSArray* data = @[@"Grapes", @"Apples", @"Oranges"];

如果您想对其进行排序,只需将描述符的键传入nil,并调用我上面提到的方法即可:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
data = [data sortedArrayUsingDescriptors:@[descriptor]];

输出将如下所示:

输出将如下所示:

Apples, Grapes, Oranges

更多细节请查看this

1
NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; // Describe the Key value using which you want to sort. 
NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor]; // Add the value of the descriptor to array.
sortedArrayWithName = [yourDataArray sortedArrayUsingDescriptors:descriptors]; // Now Sort the Array using descriptor.

在这里您将获得已排序的数组列表。


0
使用NSSortDescriptor类,你将得到这里的所有内容。

0

也许这可以帮助你:

[myNSMutableArray sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES],[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]]];

一切都遵循NSSortDescriptor的规则...


0
NSSortDescriptor * sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name_your_key_value" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
NSArray * sortedArray;
sortedArray = [Your_array sortedArrayUsingDescriptors:sortDescriptors];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接