PerformSelector warning

2019-01-17 17:49发布

I'm receiving a warning

PerformSelector may cause a leak because its selector is unknown

In the code:

- (void) callDelegate: (SEL) selector withArg: (id) arg error: (NSError*) err
{
    assert([NSThread isMainThread]);
    if([delegate respondsToSelector: selector])
    {
        if(arg != NULL)
        {
            //this line the warning
            [delegate performSelector: selector 
                           withObject: arg 
                           withObject: err]; 
        }
        else
        {
            //this line the warning
            [delegate performSelector: selector 
                           withObject: err]; 
        }
    }
    else
    {
        NSLog(@"Missed Method");
    }
}

Header:

@interface Topscore : UIViewController <NSObject> {

//
}

5条回答
倾城 Initia
2楼-- · 2019-01-17 18:06

This is a warning generated by the compiler because -Wundeclared-selector was used while compiling and automatic reference counting (ARC) is enabled. This can be, in general, safely ignored, as it's obvious that the selector in the variable named "selector" is unknown at compile time, as it will have its value assigned at runtime.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-17 18:09

Your if ... respondsToSelector: selector won't work because your selector is just the name of the method. For your case you need to check

if ([delegate respondsToSelector: @selector(method::)]

and for the other case just for method:.

Anyway, you can supress the warning like this:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [self performSelector:nextView];
#pragma clang diagnostic pop
查看更多
看我几分像从前
4楼-- · 2019-01-17 18:11

Easiest way is adding this macro to your pch File. Or .m file..

#pragma GCC diagnostic ignored "-Wundeclared-selector"
查看更多
仙女界的扛把子
5楼-- · 2019-01-17 18:27

You could add -Wno-arc-performSelector-leaks for WARNING_CFLAGS in the Build Settings. enter image description here

Found the solution here

查看更多
男人必须洒脱
6楼-- · 2019-01-17 18:33

You can also use objc_msgSend instead of performSelector, as described here.

查看更多
登录 后发表回答