why warning with my performSelector

2019-08-03 01:43发布

Below is a simple PerformSelector that sends a message to obj to perform the looping method. All works well but I get the following yellow warning.

PerformSelector may cause a leak because its selector is unknown.

#import "MyClass.h"
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        MyClass *obj = [[MyClass alloc]init];

        SEL mySel = @selector(looping);
        [obj performSelector:mySel];
    }
    return 0;
}

This warning does not make sense because the performSelector must be aware of mySel because the looping method does get called - any ideas whats going on ??


Update

MyClass.h

#import <Foundation/Foundation.h>

@interface MyClass : NSObject

-(void)looping;

@end

MyClass.m

#import "MyClass.h"

@implementation MyClass

-(void)looping{

    NSLog(@"Hey, i'm looping");

}

@end

2条回答
2楼-- · 2019-08-03 02:38

Update -- The Real Answer

This is ARC specific:

performSelector may cause a leak because its selector is unknown

In short, ARC uses information based on the naming conventions and any additional attributes bound to the selector. When accessing a selector by name and performing it via the performSelector: family of methods, that information is lost and the compiler is warning you that it must make some assumptions regarding reference counting because this information is stripped away.

In short, the specific program you posted is safe but you are encouraged to use an alternative which is ARC-friendly.

The Previous Response

A selector's declaration does not need to be visible to the current translation in order to call it.

The compiler is allowed to assume default types for parameters and return types for class and instance methods (id is the default).

There are several compiler warnings which can warn you of these shady actions.

You probably forgot to declare the selector looping in the @interface, or you may have omitted the colon, if it has arguments: looping: would be its name.

查看更多
看我几分像从前
3楼-- · 2019-08-03 02:43

this warning is due to that u have not told the compiler where the selector resides, import the file where it is or add the selector to header file where it should be

查看更多
登录 后发表回答