Sorting Array Based on custom object values

血红的双手。 提交于 2019-12-08 12:57:47

问题


I Need to Sort out an array of custom objects.

The object is simple, it stores an x and y co-ordinate, for example:

XYPointObject.xCoordinate = [NSNumber];
XYPointObject.yCoordinate = [NSNumber];

I have an array that stores up to 676 of these objects that I need to sort into a numerical order as in x values in numerical order, and the y values connected to the x values in order as well. for example, if the input co-ordinates are:

23,5 | 
5,7 | 
1,4 | 
1,7 | 
21,8 | 
9,12 | 
16,19

the sorted array would have the order

1,4 | 1,7 | 5,7 | 9,12 | 16,19 | 23,5 

keep in mind the max x,y co-ordinants are 25 (25,25)


回答1:


Did you even take a look at the documentation?

Here's the method that you need:

-[NSArray sortedArrayUsingComparator:]



回答2:


Use:

NSSortDescriptor *xSorter = [[NSSortDescriptor alloc] initWithKey:@"xCoordinate" ascending:YES];
NSSortDescriptor *ySorter = [[NSSortDescriptor alloc] initWithKey:@"yCoordinate" ascending:YES];
NSArray *sortedArray=[array sortedArrayUsingDescriptors:@[xSorter,ySorter]];


来源:https://stackoverflow.com/questions/15610434/sorting-array-based-on-custom-object-values

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