Implicit conversion of 'BOOL' (aka 'signed char') to 'id' ,objc_setAssociatedObject

戏子无情 提交于 2019-12-10 17:16:16

问题


I am using an associated reference as storage for a property of my category

header file contains :

@interface UIImageView (Spinning)

@property (nonatomic, assign) BOOL animating;

@end

implementation is

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

However, I am getting the warning for the line above

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

if you know what I am doing wrong here, please help how to avoid this problematic


回答1:


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

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

Try:

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

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

Update: Using modern Objective-C you can do:

objc_setAssociatedObject(self, animatingKey, @(value), OBJC_ASSOCIATION_RETAIN_NONATOMIC);



回答2:


void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)

objc_setAssociatedObject accepts id type of value as third parameter and you are trying to pass BOOL to it. So make conversion as needed.



来源:https://stackoverflow.com/questions/14918125/implicit-conversion-of-bool-aka-signed-char-to-id-objc-setassociatedobj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!