我遇到了 isEqual 的问题:
编码:
if (currentAnchor isEqual:currentBusiness.getCllLocation))
{
do a;
}
else
{
do b;
}
currentanchor 和 currentbusiness.getCllocation 是位置
但是如果它们相同,为什么要调用函数 b 呢?我的代码有问题吗?
我遇到了 isEqual 的问题:
编码:
if (currentAnchor isEqual:currentBusiness.getCllLocation))
{
do a;
}
else
{
do b;
}
currentanchor 和 currentbusiness.getCllocation 是位置
但是如果它们相同,为什么要调用函数 b 呢?我的代码有问题吗?
我假设这两个对象都是类型CLLocation
,基于getClLocation
.
CLLocation
没有任何关于它的isEqual:
方法做什么的规范,所以它很可能只是继承了 的实现NSObject
,它只是比较对象的指针。如果您有两个具有相同数据的不同对象,则该isEqual:
实现将返回NO
. 如果你有两个不同的物体,它们的位置只有轻微的变化,它们肯定不会相等。
isEqual:
比较位置对象时您可能不想要。相反,您可能希望distanceFromLocation:
在CLLocation
. 像这样的东西会更好:
CLLocationDistance distanceThreshold = 2.0; // in meters
if ([currentAnchor distanceFromLocation:currentBusiness.getCllLocation] < distanceThreshold)
{
do a;
}
else
{
do b;
}
有一阵子了。
我所做的与 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
我很惊讶我会问这个问题:)
isEqual
只检查对象而不是它们的内容。您需要创建自己的方法来访问对象的变量并使用==
运算符检查它们是否相等。
斯威夫特 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
}