我正在使用sortedArrayUsingSelector对我拥有的数组进行排序。
我在这称呼它:
NSArray *sortedArray;
SEL sel = @selector(intSortWithNum1:withNum2:withContext:);
sortedArray = [_myObjs sortedArrayUsingSelector:sel];
这是定义:
- (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;
}
当我运行我的应用程序时,我的main中出现了thread1 SIGABRT错误。
有什么想法吗?提前谢谢。
注意:我已经尝试过这个:
NSArray *sortedArray = [[NSArray alloc] init];
它没有解决任何问题。
答案 0 :(得分:2)
选择器应该由被比较的对象实现,并且应该只接受一个参数,这是另一个相同类型的对象。
例如,在NSArray中,有一个使用caseInsensitiveCompare比较字符串的示例。那是因为NSString实现了caseInsensitiveCompare。
如果你想到它... sortedArrayUsingSelector如何知道在你的例子中作为参数传递什么???
编辑: 这意味着您用作“排序选择器”的函数必须是由数组中的对象定义的函数。假设您的数组包含Persons,您的数组必须按如下方式排序:
sortedArray = [_myObjs sortedArrayUsingSelector:@selector(comparePerson:)];
comparePerson消息将被发送到数组中的对象(Persons),因此在Person的类中,你必须有一个名为comparePerson的函数:
- (NSComparisonResult)comparePerson:(Person *)person
{
if (self.age == person.age)
return NSOrderedSame;
}
在这个例子中,comparePerson将自己(self)与参数(person)进行比较,如果两个人的年龄相同,则认为两个人相等。如您所见,只要您编写正确的逻辑,这种比较和排序方式就会非常强大。