按对象的属性对NSMutableArray进行排序 [英] Sorting NSMutableArray By Object's Property
问题描述
因此,对于自定义对象的 NSMutableArray
进行排序的最佳方法,这是一个相当基本的问题。
So this is a rather basic question regarding the best way to sort an NSMutableArray
of custom objects.
我有一个 NSMutableArray
的自定义对象,每个对象都有一个 NSString
和 NSDate
一起去。我需要按最新的对象排序数组(所以最新的 NSDate
),我很确定我可以简单地使用 NSDate比较:NSDate
如果这是一个只有 NSDate
的数组,但由于我需要对所有对象进行排序而不仅仅是日期,我不确定我是否可以使用该方法。
I have a an NSMutableArray
of custom objects, each object with an NSString
and NSDate
that go together. I need to sort the array by the newest object (so latest NSDate
), and I'm pretty sure I could simply use NSDate compare: NSDate
if this was an array of just NSDate
, but since I need all objects to be sorted and not just the date, I'm not sure if I can use that method.
就伪代码而言,我需要:查看单个对象,确定当前对象的 NSDate
是数组中的下一个最大值,如果是,则移动对象,而不仅仅是日期。
In terms of pseudo-code, I need to: Look at individual object, determine if the current object's NSDate
is the next biggest in the array, and if it is, move the object, not just the date.
再次,这是我甚至是犹豫不决,因为它是如此基本,但我不想写一些非常低效的方法,如果有一个预先存在的类方法基本上做我想要的,搜索对象的子属性数组并根据对象排序subproperties。
Again, this is something I was even hesitant to ask since it's so basic but I don't want to go writing some grossly inefficient method if there is a pre-existing class method that will essentially do what I want, search an array of object's sub properties and sort the objects according to the subproperties.
感谢您的帮助。
推荐答案
NSSortDescriptors
s简单。使用 NSMutableArray
,您可以使用 sortUsingDescriptors:
对现有数组进行排序,并使用不可变数组使用<$ c创建新数组$ c> sortedArrayUsingDescriptors:
NSSortDescriptors
s make this really simple. With NSMutableArray
you can sort the existing array using sortUsingDescriptors:
and with immutable arrays you create a new array using sortedArrayUsingDescriptors:
//This will sort by stringProperty ascending, then dateProperty ascending
[mutable_array sortUsingDescriptors:
@[
[NSSortDescriptor sortDescriptorWithKey:@"stringProperty" ascending:YES],
[NSSortDescriptor sortDescriptorWithKey:@"dateProperty" ascending:YES]
]];
这篇关于按对象的属性对NSMutableArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!