简体   繁体   English

如何根据一个属性对对象的 NSArray 进行排序

[英]How to sort NSArray of objects based on one attribute

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.它们需要排序的属性是 object (NSString) 的名称,它是托管属性之一。 Currently I am putting all of the names in an array of strings and then using sortedNameArray = [sortedNameArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];目前我将所有名称放在一个字符串数组中,然后使用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?我应该如何 go 这样做?

Use NSSortDescriptor.使用 NSSortDescriptor。 Just search the documentation on it and there some very simple examples you can copy right over.只需搜索它的文档,您可以直接复制一些非常简单的示例。 Here is a simplified example:这是一个简化的示例:

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.就像你有一个排序数组一样。

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];`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM