我得到ARC编译器的以下警告:

"performSelector may cause a leak because its selector is unknown".

这是我正在做的:

[_controller performSelector:NSSelectorFromString(@"someMethod")];

为什么我得到这个警告?我理解编译器不能检查选择器是否存在,但为什么会导致泄漏?我怎样才能改变我的代码,让我不再得到这个警告呢?


当前回答

您还可以在这里使用协议。因此,创建一个这样的协议:

@protocol MyProtocol
-(void)doSomethingWithObject:(id)object;
@end

在需要调用选择器的类中,有一个@属性。

@interface MyObject
    @property (strong) id<MyProtocol> source;
@end

当你需要在MyObject的实例中调用@selector(doSomethingWithObject:)时,这样做:

[self.source doSomethingWithObject:object];

其他回答

您还可以在这里使用协议。因此,创建一个这样的协议:

@protocol MyProtocol
-(void)doSomethingWithObject:(id)object;
@end

在需要调用选择器的类中,有一个@属性。

@interface MyObject
    @property (strong) id<MyProtocol> source;
@end

当你需要在MyObject的实例中调用@selector(doSomethingWithObject:)时,这样做:

[self.source doSomethingWithObject:object];

我没有使用块方法,这给我带来了一些问题:

    IMP imp = [_controller methodForSelector:selector];
    void (*func)(id, SEL) = (void *)imp;

我将使用NSInvocation,像这样:

    -(void) sendSelectorToDelegate:(SEL) selector withSender:(UIButton *)button 

    if ([delegate respondsToSelector:selector])
    {
    NSMethodSignature * methodSignature = [[delegate class]
                                    instanceMethodSignatureForSelector:selector];
    NSInvocation * delegateInvocation = [NSInvocation
                                   invocationWithMethodSignature:methodSignature];


    [delegateInvocation setSelector:selector];
    [delegateInvocation setTarget:delegate];

    // remember the first two parameter are cmd and self
    [delegateInvocation setArgument:&button atIndex:2];
    [delegateInvocation invoke];
    }

为了让Scott Thompson的宏更通用:

// String expander
#define MY_STRX(X) #X
#define MY_STR(X) MY_STRX(X)

#define MYSilenceWarning(FLAG, MACRO) \
_Pragma("clang diagnostic push") \
_Pragma(MY_STR(clang diagnostic ignored MY_STR(FLAG))) \
MACRO \
_Pragma("clang diagnostic pop")

然后这样使用它:

MYSilenceWarning(-Warc-performSelector-leaks,
[_target performSelector:_action withObject:self];
                )

在编译器允许覆盖警告之前,可以使用运行时作为一种变通方法。

你需要标题:

#import <objc/message.h>

然后试试下面的方法:

// For strict compilers.
((id(*)(id,SEL))objc_msgSend)(_controller, sel_getUid("someMethod"));

OR

// Old answer's code:
objc_msgSend(_controller, NSSelectorFromString(@"someMethod"));

而不是:

[_controller performSelector:NSSelectorFromString(@"someMethod")];

在项目生成设置中,在其他警告标志(WARNING_CFLAGS)下添加 -Wno-arc-performSelector-leaks

现在只需确保所调用的选择器不会导致对象被保留或复制。