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

时间:2011-01-18 11:49:58

标签: iphone objective-c nsmutablearray

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

7 个答案:

答案 0 :(得分:95)

您可以这样做来排序NSMutableArray:

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

答案 1 :(得分:47)

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

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

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

答案 2 :(得分: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.

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

答案 3 :(得分:0)

使用NSSortDescriptor课程休息,您将获得所有内容here

答案 4 :(得分: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];

答案 5 :(得分:0)

也许这可以帮到你:

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

全部是根据NSSortDescriptor ......

答案 6 :(得分:0)

在最简单的场景中,如果你有一个字符串数组:

NSArray* data = @[@"Grapes", @"Apples", @"Oranges"];

如果你想对它进行排序,你只需传入 nil 作为描述符的键,然后调用我上面提到的方法:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
data = [data sortedArrayUsingDescriptors:@[descriptor]];

输出如下所示:

Apples, Grapes, Oranges

有关详细信息,请查看 this

相关问题