Any gotchas with objc_setAssociatedObject and objc_getAssociatedObject?

自古美人都是妖i 提交于 2019-11-29 14:43:25

问题


I’m looking into ways to add a property (an integer in this case) to all UIView instances, whether they are subclassed or not. Is using objc_setAssociatedObject() and objc_getAssociatedObject() within a category the appropriate, Apple-endorsed way to do this?

I have heard some concerns that this constitutes a “runtime hack,” and can lead to problems that are difficult to track down and debug. Has anyone else seen this type of problem? Is there a better way to add an integer property to all UIView instances without subclassing?

Update: I can’t just use tag, because this needs to be used in a code base that already uses tag for other things. Believe me, if I could use tag for this, I would!


回答1:


Associated objects come in handy whenever you want to fake an ivar on a class. They are very versatile as you can associate any object to that class.

That said, you should use it wisely and only for minor things where subclassing feels cumbersome.

However, if your only requirement is to add an integer to all UIView instances, tag is the way to go. It's already there and ready for you to use, so there's no need for involving run-time patching of UIView.

If you instead want to tag your UIView with something more than an integer, like a generic object, you can define a category like follows.

UIView+Tagging.h

@interface UIView (Tagging)
@property (nonatomic, strong) id customTag;
@end

UIView+Tagging.m

#import <objc/runtime.h>

@implementation UIView (Tagging)
@dynamic customTag;

- (id)customTag {
    return objc_getAssociatedObject(self, @selector(customTag));
}

- (void)setCustomTag:(id)aCustomTag {
    objc_setAssociatedObject(self, @selector(customTag), aCustomTag, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

The trick of using a property's selector as key, has recently been proposed by Erica Sadun in this blog post.




回答2:


Use tag. That's what it was meant for.



来源:https://stackoverflow.com/questions/16019782/any-gotchas-with-objc-setassociatedobject-and-objc-getassociatedobject

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