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

2020-02-23 10:35发布

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!

6条回答
对你真心纯属浪费
2楼-- · 2020-02-23 11:19

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.

查看更多
smile是对你的礼貌
3楼-- · 2020-02-23 11:20

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

查看更多
够拽才男人
4楼-- · 2020-02-23 11:23
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.

查看更多
Bombasti
5楼-- · 2020-02-23 11:24

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

查看更多
欢心
6楼-- · 2020-02-23 11:24

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.

查看更多
女痞
7楼-- · 2020-02-23 11:33

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)

查看更多
登录 后发表回答