I';我用Objective-C和ARC编写了一个Button类——如何防止叮当声';选择器上的内存泄漏警告?

I';我用Objective-C和ARC编写了一个Button类——如何防止叮当声';选择器上的内存泄漏警告?,objective-c,clang,automatic-ref-counting,Objective C,Clang,Automatic Ref Counting,我正在编写一个简单的button类,如下所示: @interface MyButton : NSObject { id object; SEL action; } @property(strong) id object; @property SEL action; -(void)fire; @end @implementation MyButton @synthesize object, action; -(void)fire { [object performSelecto

我正在编写一个简单的button类,如下所示:

@interface MyButton : NSObject {
  id object;
  SEL action;
}
@property(strong) id object;
@property SEL action;
-(void)fire;
@end


@implementation MyButton

@synthesize object, action;

-(void)fire {
  [object performSelector:action];
}

@end
我从[object performSelector:action]上的叮当声中得到以下警告:

PerformSelector may cause a leak because its selector is unknown
在我看到选择器可以属于具有不同内存需求的系列之后。其目的是让操作返回void,因此它不应该导致任何ARC困难,并且应该适合
none
系列

看起来我想要的相关预处理器代码是,或者是:

__attribute__((objc_method_family(none)))

但是我应该把它放在哪里,告诉Clang不要担心?

如果您正在编写新代码,处理回调的最佳方法是使用块;它们比performSelector更安全、更灵活。请参阅。

因为您正在动态分配
操作
,编译器会发现ARC可能存在漏洞。将来,LLVM编译器可能允许您抑制警告。在此之前,您可以使用运行时的
objc\u msgSend()
而不是
-performSelector:
来避免警告


首先,在Xcode 4.2的LLVM 3.0编译器中导入运行时消息头,您可以按如下方式抑制警告:

#import <objc/message.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [object performSelector:action];
#pragma clang diagnostic pop
感谢斯科特·汤普森(关于这个类似的问题:)的回答。

我用这个:

[object tryToPerform:action with:nil];

类似的问题根类方面是一个复制粘贴和编辑打字错误。这是出于实用的原因我最终采取的方法,但我会保留这个问题,以防问题有答案。毕竟,performSelector仍然在工具箱中占有一席之地。
[object tryToPerform:action with:nil];