Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C sub-classing basics, how to add custom property;

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!

like image 596
Zebs Avatar asked Mar 13 '11 02:03

Zebs


4 Answers

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.

like image 140
skue Avatar answered Oct 26 '22 10:10

skue


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)

like image 24
hoha Avatar answered Oct 26 '22 08:10

hoha


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

like image 33
oblApps Avatar answered Oct 26 '22 08:10

oblApps


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.

like image 31
Alexsander Akers Avatar answered Oct 26 '22 10:10

Alexsander Akers