任何与objc_setAssociatedObject和objc_getAssociatedObject的陷阱? [英] Any gotchas with objc_setAssociatedObject and objc_getAssociatedObject?
问题描述
我正在研究如何将属性(在本例中为整数)添加到所有 UIView
实例,无论它们是否为子类。在类别中使用 objc_setAssociatedObject()
和 objc_getAssociatedObject()
是否采用Apple认可的相应方式?
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?
我听到一些担心这构成了运行时黑客,并且可能导致难以追踪和调试的问题。有没有人见过这类问题?是否有更好的方法将整数属性添加到所有 UIView
实例而不进行子类化?
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!
推荐答案
每当你想在一个类上伪造一个ivar时,相关的对象会派上用场。它们非常通用,因为你可以将任何对象与该类相关联。
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.
但是,如果您的唯一要求是向所有 UIView
实例添加一个整数,标签
是要走的路。它已经存在并且可供您使用,因此无需涉及 UIView
的运行时修补。
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
.
如果你想要用超过整数的东西来标记你的 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.
@interface UIView (Tagging)
@property (nonatomic, strong) id customTag;
@end
UIView + Tagging.m
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
使用房产的诀窍选择器作为关键,最近由Erica Sadun在此博文中提出。
The trick of using a property's selector as key, has recently been proposed by Erica Sadun in this blog post.
这篇关于任何与objc_setAssociatedObject和objc_getAssociatedObject的陷阱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!