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

As the name says. When I do this, everything will go wrong right away:

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

Are there good reasons to be careful in using?

+3
source share
2 answers

You use the API in a way that is not explicitly supported by the document. Thus, you cannot complain when it breaks in the next OS X / iOS update. This is one reason for caution.

The documentation says it OBJC_ASSOCIATION_ASIGNsets up a weak link. This means a non-trivial thing in a garbage collection situation, so be careful.

, . NSStringFromSelector .

+6

. , API, . , NSValue 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);
}
+3

All Articles