Sorting NSMutableArray By Object's Property

喜你入骨 提交于 2019-11-30 07:45:03

问题


So this is a rather basic question regarding the best way to sort an NSMutableArray of custom objects.

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.

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.

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.

Thanks for any help.


回答1:


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



回答2:


This little snippet worked great for me:

[students sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]];


来源:https://stackoverflow.com/questions/7001597/sorting-nsmutablearray-by-objects-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!