我想对一个NSMutableArray对象按字母顺序进行排序。
我想对一个NSMutableArray对象按字母顺序进行排序。
您可以使用以下方法对NSMutableArray进行排序:
[yourArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
这里提供的其他答案提到使用@selector(localizedCaseInsensitiveCompare:)。
对于NSString数组,这很有效, 但是OP评论说该数组包含对象,并且应根据对象的name属性进行排序。
在这种情况下,您应该执行以下操作:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[yourArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
您的对象将根据这些对象的名称属性进行排序。
NSArray* data = @[@"Grapes", @"Apples", @"Oranges"];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
data = [data sortedArrayUsingDescriptors:@[descriptor]];
输出将如下所示:
Apples, Grapes, Oranges
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.
在这里您将获得已排序的数组列表。
也许这可以帮助你:
[myNSMutableArray sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES],[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]]];
一切都遵循NSSortDescriptor的规则...
NSSortDescriptor * sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name_your_key_value" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray * sortedArray;
sortedArray = [Your_array sortedArrayUsingDescriptors:sortDescriptors];