第一种解决办法:
As a workaround until the compiler allows overriding the warning, you can use the runtime
objc_msgSend(_controller, NSSelectorFromString(@"someMethod"));
instead of
[_controller performSelector:NSSelectorFromString(@"someMethod")];
You'll have to
#import <objc/message.h>
第二种:
To ignore the error only in the file with the perform selector, add a #pragma as follows:
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
第三种:
#define SUPPRESS_PERFORM_SELECTOR_LEAK_WARNING(code) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
code; \
_Pragma("clang diagnostic pop") \
SUPPRESS_PERFORM_SELECTOR_LEAK_WARNING(
return [_target performSelector:_action withObject:self]
);
在Objective-C中需要以函数名或者函数指针来调用函数时,以回调函数为例,对象为(id)target,它的成员函数名为callback,之前习惯是这么写的:
if ([target respondsToSelector:callback]){
[target performSelector:callback withObject:nil];
}
但是在ARC下会报一个warning: PerformSelector may cause a leak because its selector is unknown
在网上查,很多人说的方法都是定义宏去ignore warning之类的。总感觉很不爽。今天查到了正确的解决方法:
【解决方法】
if ([target respondsToSelector:callback]){
// [target performSelector:callback withObject:nil];
IMP imp = [target methodForSelector:callback];
void (*func)(id, SEL) = (void *)imp;
func(target, callback);
}
这样就不会报warning了。