本文介绍了Objective-C子类化基础知识,如何添加自定义属性;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题的子类。

I am having a issue subclassing MKPolygon.

我想添加一个简单的 int标签属性但我一直在获取MKPolygon的实例而不是我的自定义类,所以调用 setTag:会导致异常。

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.

问题是使用类方法创建MKPolygons: polygonWithCoordinates:count:我不知道如何将其转换为我的类的实例(包括标记属性) 。

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).

您如何向MKPolygon添加标签属性?

How would you go about adding a tag property to MKPolygon?

谢谢!

推荐答案

你们都应该使用一个类别(如@Seva建议)和objc_setAssociatedObject(如@hoha建议的那样)。

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

你可能还想看看在,除了@hoha链接到的API。

You may also want to look at Associative References section of the ObjC Guide, in addition to the API @hoha linked to.

这篇关于Objective-C子类化基础知识,如何添加自定义属性;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 01:44