Reputation: 660
I'm using sortedArrayUsingSelector to sort an array I have.
Here's me calling it:
NSArray *sortedArray;
SEL sel = @selector(intSortWithNum1:withNum2:withContext:);
sortedArray = [_myObjs sortedArrayUsingSelector:sel];
And here's the definition:
- (NSInteger) intSortWithNum1:(id)num1 withNum2:(id)num2 withContext:(void *)context {
CLLocationCoordinate2D c1 = CLLocationCoordinate2DMake([((myObj *)num1) getLat], [((myObj *)num1) getLong]);
CLLocationCoordinate2D c2 = CLLocationCoordinate2DMake([((myObj *)num2) getLat], [((myObj *)num2) getLong]);
NSUInteger v1 = [self distanceFromCurrentLocation:(c1)];
NSUInteger v2 = [self distanceFromCurrentLocation:(c2)];
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
I'm getting the thread1 SIGABRT error in my main when I run my app.
Any ideas? Thanks in advance.
Note: I have already tried this:
NSArray *sortedArray = [[NSArray alloc] init];
It didn't fix anything.
Upvotes: 0
Views: 137
Reputation: 8180
The selector should be implemented by the objects being compared, and should take just one argument which is another object of the same type.
For example, in NSArray, there's an example where strings are being compared using caseInsensitiveCompare. That's because NSString implements caseInsensitiveCompare.
If you think of it... how can sortedArrayUsingSelector know what to pass as parameters to the function in your example??
EDIT: That means that the function you use as the 'sorting selector' must be a function defined by the objects in your array. Suppose if your array contains Persons, your array must be sorted like this:
sortedArray = [_myObjs sortedArrayUsingSelector:@selector(comparePerson:)];
The comparePerson message will be sent to the objects in your array (Persons), so in your Person's class you must have a function called comparePerson:
- (NSComparisonResult)comparePerson:(Person *)person
{
if (self.age == person.age)
return NSOrderedSame;
}
In this example, comparePerson compares itself (self) with the argument (person), and considers two persons equal if they have the same age. As you can see, this way of comparing and sorting can be very powerful, provided that you code the proper logic.
Upvotes: 2