Any gotchas with objc_setAssociatedObject and objc_getAssociatedObject?

后端 未结 2 861
时光取名叫无心
时光取名叫无心 2021-01-01 01:42

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_setAssociated

相关标签:
2条回答
  • 2021-01-01 02:01

    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.

    0 讨论(0)
  • 2021-01-01 02:18

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

    0 讨论(0)
提交回复
热议问题