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

落花浮王杯 提交于 2019-11-29 02:56:05

问题


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!


回答1:


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.




回答2:


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)




回答3:


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




回答4:


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.




回答5:


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.




回答6:


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



来源:https://stackoverflow.com/questions/5286961/objective-c-sub-classing-basics-how-to-add-custom-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!