How do I test the equality of two CLLocations
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?
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;
}
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 :)
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.
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
}
精彩评论