Implicit conversion of 'BOOL' (also known as char ') to' id ', objc_setAssociatedObject

I use linked link as storage for property of my category

header file contains:

@interface UIImageView (Spinning) @property (nonatomic, assign) BOOL animating; @end 

implementation

 - (void)setAnimating:(BOOL)value { objc_setAssociatedObject(self, animatingKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } 

However, I get a warning for the line above

 Implicit conversion of 'BOOL' (aka 'signed char') to 'id' is disallowed with ARC 

if you know what I'm doing wrong here, please help how to avoid this problem

+4
source share
2 answers

The objc_setAssociatedObject function expects an Objective-C object for the third parameter. But you are trying to pass a non-object BOOL value.

This is no different than trying to add BOOL to NSArray . You need to wrap BOOL .

Try:

 objc_setAssociatedObject(self, animatingKey, [NSNumber numberWithBool:value], OBJC_ASSOCIATION_RETAIN_NONATOMIC); 

Of course, you will need to extract the BOOL value from NSNumber when you get the associated object later.

Update. Using modern Objective-C, you can:

 objc_setAssociatedObject(self, animatingKey, @(value), OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
+19
source
 void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy) 

objc_setAssociatedObject takes the id type as the third parameter, and you are trying to pass a BOOL to it. Therefore, if necessary, do the conversion.

0
source

All Articles