NSArray Sort

I have NSArray objects. These objects have an int attribute called "distance". I would like to sort the array by distance.

Can someone please tell me how to do this? I cannot understand how the sortUsingSelector or sortUsingDescriptor methods work ...

thanks

+4
source share
2 answers

I assume you are using NSMutableArray because NSArray is immutable.

When you sort something, you want the end result to be organized as

x1 <= x2 <= x3 <= x4 <= ... <= xN 

How to determine this <= ? ObjC has 3 solutions.


1. -sortUsingSelector:

[arr sortUsingSelector:@selector(foo:)] means that its elements will be compared as *

 x <= y is equivalent to [x foo:y] <= 0 

For example, to sort the list of strings case-insensitively, you use [arr sortUsingSelector:@selector(caseInsensitiveCompare:)] .


2. -sortUsingFunction:context:

This is similar to -sortUsingSelector: but a function pointer is used as input. [arr sortUsingFunction:funcptr context:ctx] means that its elements will be compared as

 x <= y is equivalent to funcptr(x, y, ctx) <= 0 

3. -sortUsingDescriptors:

This is the most difficult question. It accepts a list of NSSortDescriptors that describe the expected order of properties. One basic example:

 NSSortDescriptor* desc = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES]; [arr sortUsingDescriptors:[NSArray arrayWithObject:desc]]; [desc release]; 

the handle tells the sort routine to "sort by distance in ascending order."

Suppose there are 2 keys, the integers x incrementing, and then the lines y descending, then you can write

 NSSortDescriptor* dx = [[NSSortDescriptor alloc] initWithKey:@"x" ascending:YES]; NSSortDescriptor* dy = [[NSSortDescriptor alloc] initWithKey:@"y" ascending:NO selector:@selector(caseInsensitiveCompare:)]; [arr sortUsingDescriptors:[NSArray arrayWithObjects:x, y, nil]]; [dx release]; [dy release]; 

etc.


Note: * In fact, you should only return -1, 0, or 1.

+27
source

Finnaly, I learned how to do this:

after @implementation:

 static NSInteger sort(Myclass *obj1, Myclass *obj2, void *context) { if(obj1.distance < obj2.distance) return NSOrderedAscending; else if(obj1.distance > obj2.distance) return NSOrderedDescending; else return NSOrderedSame; 

Then, where you need to sort the NSArray:

 NSArray *sortedArray = [unsortedArray sortedArrayUsingFunction:sort context:NULL]; 
+3
source

Source: https://habr.com/ru/post/1310001/


All Articles