I have an Array of MKAnnotation objects called arrAnnotations. I want to pick out one of the annotations with the same coordinate as the one stored in a CLLocation object called “newLocation”.
I’m trying to use a NSPredicate, but it doesn’t work.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF.coordinate == %f)", newLocation.coordinate];
NSArray* filteredArray = [arrAnnotations filteredArrayUsingPredicate:predicate];
[self.mapView selectAnnotation:[filteredArray objectAtIndex:0] animated:YES];
The filteredArray always contains zero objects.
I have also tried the following, which do not work either
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(coordinate == %f)", newLocation.coordinate];
and
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(coordinate > 0)"];
and
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(coordinate.latitude == %f)", newLocation.coordinate.latitude];
The last two crash the app, the third one with an NSInvalidArgumentException for [NSConcreteValue compare:] and the fourth, because latitude is not key-value-coding-compliant (I assume this is because coordinate is just a c-struct and not an NSObject?).
How can I make this work with NSPredicate?
Can anyone give me a link to a document that shows how Predicates work under the hood?
I don’t understand what they actually do, even though I have read and understood most of Apple’s Predicate Programming Guide.
Is searching a huge array with predicates more efficient than just looping through it with a for…in construct? If yes/no, why?
MKAnnotation protocol’s coordinate property is a CLLocationCoordinate2D
struct, thus it is not allowed inNSPredicateformat syntax according to the Predicate Format String SyntaxYou could use
NSPredicatepredicateWithBlock:instead to accomplish what you are trying to do, but you have be careful withCLLocationCoordinate2Dand how to compare it for equality.CLLocationCoordinate2D‘slatitudeandlongitudeproperty are CLLocationDegrees data type, which is adoubleby definition.With a quick search you can find several examples of problems you would face when comparing floating point values for equality. Some good examples can be found here, here and here.
Given all that, I believe that using code bellow for your predicate might solve your problem.