gpt4 book ai didi

iphone - NSSortDescriptor 用于比较 Cocoa/iPhone 中的 CLLocation 对象

转载 作者:行者123 更新时间:2023-12-03 16:16:00 25 4
gpt4 key购买 nike

我有一个 CLLocation 对象数组,我希望能够比较它们以获取与起始 CLLocation 对象的距离。数学很简单,但我很好奇是否有一个方便的排序描述符来执行此操作?我应该避免 NSSortDescriptor 并编写自定义比较方法 + 冒泡排序吗?我通常最多比较 20 个对象,因此不需要非常高效。

最佳答案

您可以为 CLLocation 编写一个简单的compareToLocation:类别,根据自身与另一个 CLLocation 对象之间的距离返回 NSOrderedAscending、NSOrderedDescending 或 NSOrderedSame。然后简单地做这样的事情:

NSArray * mySortedDistances = [myDistancesArray sortedArrayUsingSelector:@selector(compareToLocation:)];

编辑:

像这样:

//CLLocation+DistanceComparison.h
static CLLocation * referenceLocation;
@interface CLLocation (DistanceComparison)
- (NSComparisonResult) compareToLocation:(CLLocation *)other;
@end

//CLLocation+DistanceComparison.m
@implementation CLLocation (DistanceComparison)
- (NSComparisonResult) compareToLocation:(CLLocation *)other {
CLLocationDistance thisDistance = [self distanceFromLocation:referenceLocation];
CLLocationDistance thatDistance = [other distanceFromLocation:referenceLocation];
if (thisDistance < thatDistance) { return NSOrderedAscending; }
if (thisDistance > thatDistance) { return NSOrderedDescending; }
return NSOrderedSame;
}
@end


//somewhere else in your code
#import CLLocation+DistanceComparison.h
- (void) someMethod {
//this is your array of CLLocations
NSArray * distances = ...;
referenceLocation = myStartingCLLocation;
NSArray * mySortedDistances = [distances sortedArrayUsingSelector:@selector(compareToLocation:)];
referenceLocation = nil;
}

关于iphone - NSSortDescriptor 用于比较 Cocoa/iPhone 中的 CLLocation 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1081050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com