PerformSelector may cause a leak because its selector is unknown 解决方法

第一种解决办法:

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了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值