【发布时间】:2011-01-18 11:49:58
【问题描述】:
我想按字母顺序对 NSMutableArray 进行排序。
【问题讨论】:
-
数组中对象的类型是什么?
-
我将一个对象存储在数组中,我想根据 object.name 字段对数组进行排序
标签: iphone objective-c nsmutablearray
我想按字母顺序对 NSMutableArray 进行排序。
【问题讨论】:
标签: iphone objective-c nsmutablearray
您可以这样做来对 NSMutableArray 进行排序:
[yourArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
【讨论】:
此处提供的其他答案提到使用 @selector(localizedCaseInsensitiveCompare:)
这对于 NSString 数组非常有用,但是 OP 评论说该数组包含对象并且应该根据 object.name 属性进行排序。
在这种情况下,您应该这样做:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[yourArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
您的对象将根据这些对象的名称属性进行排序。
【讨论】:
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.
在这里你会得到排序后的数组列表。
【讨论】:
在最简单的场景中,如果你有一个字符串数组:
NSArray* data = @[@"Grapes", @"Apples", @"Oranges"];
如果你想对它进行排序,你只需传入 nil 作为描述符的键,然后调用我上面提到的方法:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
data = [data sortedArrayUsingDescriptors:@[descriptor]];
输出如下所示:
Apples, Grapes, Oranges
更多详情请查看this
【讨论】:
使用NSSortDescriptor 类并休息,你会得到所有东西here
【讨论】:
NSSortDescriptor * sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Name_your_key_value" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray * sortedArray;
sortedArray = [Your_array sortedArrayUsingDescriptors:sortDescriptors];
【讨论】:
也许这可以帮助你:
[myNSMutableArray sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES],[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]]];
所有都是根据 NSSortDescriptor...
【讨论】: