views:

331

answers:

1

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

Specifically I'm looking at comparing two objects conforming to MKAnnotation (iPhone mapkit annotations). Given two objects that conform to the protocol, I would like to determine if they are equal as far as the protocol is concerned. In this case, that would mean that at least the coordinate attribute is the same.

A: 

Since CLLocationCoordinate2D is a struct, you can compare the coordinate @properties of two MKAnnotations with ==. Example:

MKAnnotation *a1;
MKAnnotation *a2;

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

With the caveat: you care comparing floating point values in the CLLocationCoordinate2D (the latitude and longitude fields of CLLocationCoordinate2D are of type CLLocation which is typdefed as double). As always, comparing two floating point values for equality is fraught with subtlety. You may want to do a more involved comparison of the latitude and longitude values independently (e.g. checking wither their absolute difference is within some small range). See Numerical Recipes for more info on this issue.

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 save caveat) would do the trick.

Barry Wark
You didn't really answer his question. Yours is specific to his example, but it looks like he wants a general solution.
Jeremy Wall
Well, he did say "specifically I'm looking at comparing two objects conforming to MKAnnotation", so I think I did at least answer his specific question.
Barry Wark
I kind of agree; I'm not sure how you can really "compare for equality based on protocol", unless you just mean you want to call -conformsToProtocol: on the instance first.
Wevah
Sijo