My managed object has 2 double fields: "latitude", "longitude". I need to fetch all objects, that has certain coordinates
This code not working, fetchedObjects count = 0
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude == %f AND longitude == %f", coordinate.latitude, coordinate.longitude];
But this code work fine, fetchedObjects count = 3:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude == 53.012667 AND longitude == 36.113000"];
it works fine with long float, %lf
Don't ever use ==
to compare floating point values.
If you want to find objects with a "specific" value, compare against a small range. Otherwise, floating-point representation error will bite you.
So consider using:
const float epsilon = 0.000001;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude > %f AND latitude < %f AND longitude > %f AND longitude < %f", coordinate.latitude - epsilon, coordinate.latitude + epsilon, coordinate.longitude - epsilon, coordinate.longitude + epsilon];
It's because the precision of floats is not 100%. So you could also do this:
[NSPredicate predicateWithFormat:@"abs(latitude - %f) < 0.0001 AND abs(longitude - %f) < 0.0001", coordinate.latitude, coordinate.longitude]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With