Chris Devereux
Chris Devereux

Reputation: 5473

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?

Upvotes: 3

Views: 459

Answers (2)

Lily Ballard
Lily Ballard

Reputation: 185841

It's a bad idea. As Yuji says, you're violating the API as defined in the documentation. If you really want to store arbitrary values, wrap then in NSValue and store that as an OBJC_ASSOCIATION_RETAIN_NONATOMIC.

- (void) associateSelector:(SEL)value withPointer:(void*)key {
    NSValue *nsvalue = [NSValue valueWithBytes:&value objcType:@encode(SEL)];
    objc_SetAssociatedObject(self, key, nsvalue, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

Upvotes: 3

Yuji
Yuji

Reputation: 34195

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.

Upvotes: 6

Related Questions