How do I test the equality of two CLLocations

徘徊边缘 提交于 2019-12-08 16:47:19

问题


I'm having a problem with isEqual:

The code:

 if (currentAnchor isEqual:currentBusiness.getCllLocation))
    {
        do a;
    }
    else
    {
        do b;
    }

currentanchor and currentbusiness.getCllocation are locations

But if they are the same, why is function b called? Is something wrong with my code?


回答1:


I assume both of these objects are of type CLLocation, based on the name of 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.

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:

CLLocationDistance distanceThreshold = 2.0; // in meters
if ([currentAnchor distanceFromLocation:currentBusiness.getCllLocation] < distanceThreshold)
{
  do a;
}
else
{
  do b;
}



回答2:


It's been a while.

What I did is similar with BJ Homer. I just add this.

@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 :)




回答3:


isEqual just check only objects not their content. you require to create your own method where you access the variables of object and check them for equality using == operator.




回答4:


Swift 4.0 version:

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
}


来源:https://stackoverflow.com/questions/6529726/how-do-i-test-the-equality-of-two-cllocations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!