Comparison / equality of two objects according to the protocol

Is there a way to compare two Objective-C objects based solely on the protocol that they implement.

In particular, I am considering comparing two objects corresponding to MKAnnotation (iPhone mapkit annotations). Given the two objects that correspond to the protocol, I would like to determine how equal they are to the protocol. In this case, this means that at least the coordinate attribute is the same.

+3
source share
1 answer

Since it CLLocationCoordinate2Dis a structure, you can compare coordinate@properties from two MKAnnotations ==. Example:

MKAnnotation *a1;
MKAnnotation *a2;

if(a1.coordinate == a2.coordinate) {
  //coordinates equal
}

With a caveat : you need to compare floating point values ​​in CLLocationCoordinate2D(the latitude and longitude fields CLLocationCoordinate2Dare of the type CLLocationthat typdefed like double). As always, comparing two floating point values ​​for equality is fraught with subtlety. You might want to make a more active comparison of latitude and longitude independently (for example, checking attenuation, their absolute difference is in a small range). For more information about this issue, see Numerical Recipes .

If you want to compare all properties, something like

(a1.coordinate == a2.coordinate) && [a1.title isEqualToString:a2.title] && [a1.subtitle isEqualToString:a2.subtitle]

(again with the reservation remaining) will do the trick.

+2

Source: https://habr.com/ru/post/1717186/


All Articles