如何基于一个属性对NSArray对象进行排序

如何基于一个属性对NSArray对象进行排序

本文介绍了如何基于一个属性对NSArray对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按字母顺序对托管对象数组进行排序。需要排序的属性是对象的名称(NSString),它是托管属性之一。目前我将所有名称放在一个字符串数组中,然后使用 sortedNameArray = [sortedNameArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare :)]; 然后将它们枚举回一个数组与对象。当两个名称相同时,这就分崩离析,所以我真的需要能够按一个属性排序。我应该怎么做?

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?

推荐答案

使用NSSortDescriptor。只需搜索它上面的文档,你可以在那里找到一些非常简单的例子。这是一个简化的例子:

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 *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.

这篇关于如何基于一个属性对NSArray对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:54