xcode 如何测试两个 CLLocations 的相等性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6529726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I test the equality of two CLLocations
提问by user4951
I'm having a problem with isEqual:
我在使用 isEqual 时遇到问题:
The code:
编码:
if (currentAnchor isEqual:currentBusiness.getCllLocation))
{
do a;
}
else
{
do b;
}
currentanchor and currentbusiness.getCllocation are locations
currentanchor 和 currentbusiness.getCllocation 是位置
But if they are the same, why is function b called? Is something wrong with my code?
但是如果它们相同,为什么会调用函数 b 呢?我的代码有问题吗?
回答by BJ Homer
I assume both of these objects are of type CLLocation
, based on the name of getClLocation
.
我假设这两个对象都是类型CLLocation
,基于getClLocation
.
CLLocation
doesn't have any specification on what its isEqual:
method does, so it's likely just inheriting the implementation of NSObject
, which simply compares the pointers of the objects. If you've got two distinct objects with identical data, that isEqual:
implementation would return NO
. And if you've got two distinct objects with just a slight variation in location, they definitely would not be equal.
CLLocation
没有关于它的isEqual:
方法做什么的任何规范,所以它可能只是继承了 的实现NSObject
,它只是比较了对象的指针。如果您有两个具有相同数据的不同对象,则该isEqual:
实现将返回NO
. 如果你有两个不同的物体,只是位置略有不同,它们肯定不会相等。
You probably don't want isEqual:
when comparing location objects. Rather, you probably want to use the distanceFromLocation:
method on CLLocation
. Something like this would be better:
isEqual:
在比较位置对象时,您可能不想要。相反,您可能希望在 上使用该distanceFromLocation:
方法CLLocation
。这样的事情会更好:
CLLocationDistance distanceThreshold = 2.0; // in meters
if ([currentAnchor distanceFromLocation:currentBusiness.getCllLocation] < distanceThreshold)
{
do a;
}
else
{
do b;
}
回答by user4951
It's been a while.
有一阵子了。
What I did is similar with BJ Homer. I just add this.
我所做的与 BJ Homer 相似。我只是添加这个。
@interface CLLocation (equal)
- (BOOL)isEqual:(CLLocation *)other;
@end
@implementation CLLocation (equal)
- (BOOL)isEqual:(CLLocation *)other {
if ([self distanceFromLocation:other] ==0)
{
return true;
}
return false;
}
@end
I was surprised I were the one asking this question :)
我很惊讶我是问这个问题的人:)
回答by Stunner
Swift 4.0 version:
斯威夫特 4.0 版本:
let distanceThreshold = 2.0 // meters
if location.distance(from: CLLocation.init(latitude: annotation.coordinate.latitude,
longitude: annotation.coordinate.longitude)) < distanceThreshold
{
// do a
} else {
// do b
}