ios 如何根据一个属性对对象的 NSArray 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6256046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort NSArray of objects based on one attribute
提问by Hymanelope11
I am trying to sort an array of managed objects alphabetically. The attribue that they need to be sorted by is the name of the object (NSString) with is one of the managed attributes. Currently I am putting all of the names in an array of strings and then using sortedNameArray = [sortedNameArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
and then enumerating them back into an array with the objects. This falls apart when two names are the same so I really need to be able to sort by one attribute. How should I go about doing this?
我正在尝试按字母顺序对一组托管对象进行排序。它们需要排序的属性是对象的名称(NSString),它是托管属性之一。目前,我将所有名称放在一个字符串数组中,然后使用sortedNameArray = [sortedNameArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
然后将它们枚举回包含对象的数组中。当两个名称相同时,这会分崩离析,所以我真的需要能够按一个属性进行排序。我该怎么做呢?
回答by Dancreek
Use NSSortDescriptor. Just search the documentation on it and there some very simple examples you can copy right over. Here is a simplified example:
使用 NSSortDescriptor。只需搜索它的文档,您就可以直接复制一些非常简单的示例。这是一个简化的示例:
NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"MyStringVariableName" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:valueDescriptor];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:descriptors];
And just like that you have a sorted array.
就像这样你有一个排序的数组。
回答by Annu
You can do this by using NSSortDescriptor,
你可以通过使用 NSSortDescriptor 来做到这一点,
eg.
例如。
`NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc]initWithKey:@"distance" ascending:YES];`
// Here I am sorting on behalf of distance. You should write your own key.
// 这里我是代表距离排序。您应该编写自己的密钥。
NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor];
NSArray *sortedArray=[yourArray sortedArrayUsingDescriptors:descriptors];`