I am having a issue subclassing MKPolygon
.
I want to add a simple int tag
property but I keep getting an instance of MKPolygon instead of my custom class, so calling setTag:
causes an exception.
The problem is that MKPolygons are created using a class method: polygonWithCoordinates: count:
and I dont know how to turn that into an instance of my class (which includes the tag property).
How would you go about adding a tag property to MKPolygon?
Thank you!
You should both use a category (as @Seva suggests) and objc_setAssociatedObject (as @hoha suggests).
You may also want to look at Associative References section of the ObjC Guide, in addition to the API @hoha linked to.
since it looks like the authors went out of their way to prevent you from subclassing (at least, that's one possible motivation for the public interface), consider using a form of composition:
http://en.wikipedia.org/wiki/Object_composition
The key is that by using the
SpecialPolygon
factory method instead of theMKPolygon
one, you'll get the desiredSpecialPolygon
subclass.I'm facing the same problem. A simple solution is to just use the Title property of the MKPolygon to save what you would save in Tag. At least in my case where I don't need an object reference but a simple number, it works
Are you talking about MKPolygons created by your code, or elsewhere? If the former, just override the polygonWithStuff method. If the latter, consider a category over MKPolygon. Then all MKPolygons in your project will have a tag in them.
Looks like developers of
MKPolygon
didn't make it inheritance friendly. If all you want is to add some tag to this instances you can1) keep a map (NSDictionary or CFDictionary) from
MKPolygon
instance addresses to tags. This solution works well if all tags are required in the same class they are set.2) use runtime to attach tag to polygons directly -
objc_setAssociatedObject
(Objective-C Runtime Reference)