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).
@interface MKPolygon (TagExtensions)
@property (nonatomic) int tag;
@end
@implementation MKPolygon (TagExtensions)
static char tagKey;
- (void) setTag:(int)tag {
objc_setAssociatedObject( self, &tagKey, [NSNumber numberWithInt:tag], OBJC_ASSOCIATION_RETAIN );
}
- (int) tag {
return [objc_getAssociatedObject( self, &tagKey ) intValue];
}
@end
You may also want to look at Associative References section of the ObjC Guide, in addition to the API @hoha linked to.
Looks like developers of MKPolygon
didn't make it inheritance friendly. If all you want is to add some tag to this instances you can
1) 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)
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
SpecialPolygon *polygon = [SpecialPolygon polygonWithCoordinates:count:];
[polygon setInt: 3];
The key is that by using the SpecialPolygon
factory method instead of the MKPolygon
one, you'll get the desired SpecialPolygon
subclass.
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