Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to use a non-id pointer as value in objc_SetAssociatedObject?

As the title says. Nothing goes wrong immediately if I do this:

- (void) associateSelector:(SEL)value withPointer:(void*)key
{
    objc_SetAssociatedObject(self, key, (id) value, OBJC_ASSOCIATION_ASSIGN);
}

Are there any good reasons to be cautious about using it?

like image 411
Chris Devereux Avatar asked Dec 17 '25 16:12

Chris Devereux


1 Answers

You're using the API in a way not explicitly supported by the document. So, you can't complain when it breaks in the next update of OS X / iOS. That's one reason to be cautious about.

The documentation says that OBJC_ASSOCIATION_ASIGN sets up a weak reference. This means a nontrivial thing in the garbage-collected situation, so beware.

If there's a way to do things in an officially supported way, I would prefer it. In your case, using NSStringFromSelector would immediately make your code supported.

like image 133
Yuji Avatar answered Dec 20 '25 08:12

Yuji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!