Iphone 如何按字母顺序对NSMutableArray排序?
我想按字母顺序对NSMutableArray进行排序。您可以这样对NSMutableArray进行排序:Iphone 如何按字母顺序对NSMutableArray排序?,iphone,objective-c,nsmutablearray,Iphone,Objective C,Nsmutablearray,我想按字母顺序对NSMutableArray进行排序。您可以这样对NSMutableArray进行排序: [yourArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 使用NSSortDescriptor类,其余的你会得到所有的东西这里提供的其他答案提到使用@selector(localizedCaseInsensitiveCompare:) 这对于NSString数组非常有效,但是OP评论说数组包含对象,
[yourArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
使用
NSSortDescriptor
类,其余的你会得到所有的东西这里提供的其他答案提到使用@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.
在这里您将获得排序数组列表。也许这可以帮助您:
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…:
NSArray* data = @[@"Grapes", @"Apples", @"Oranges"];
要对其进行排序,只需为描述符的键传入nil,然后调用我上面提到的方法:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
data = [data sortedArrayUsingDescriptors:@[descriptor]];
输出如下所示:
Apples, Grapes, Oranges
有关更多详细信息,请查看[Temppeople sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];我使用了这段代码,它给出了异常可以发布异常状态。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]堆栈的选择器无法识别:(可能对象不是NSString类型…编辑:是:-)好的,它不是字符串,问题是我正在数组中存储对象,该对象包含一个字段作为名称,我想对数组中的对象类型进行排序。数组中的对象类型是什么?我正在数组中存储一个对象,我想对数组中的对象进行排序。名称字段正是我所需要的!谢谢!这是t的更好答案他具体的问题。效果很好!