performSelector导致泄漏,因为目标c中的类型不正确



我有以下代码:

SEL moveAlongBoth = @selector(moveAlongX:andY:);
if ([p1 respondsToSelector:moveAlongBoth]) {
    [p1 performSelector: moveAlongBoth
             withObject: [NSNumber numberWithInt:1]
             withObject: [NSNumber numberWithInt:1]];
}

我收到"性能选择器可能导致泄漏"警告。但是

[p1 moveAlongX:1 andY:1];

效果很好。

我知道我得到这个错误是因为在实现中值被设置为(int),而我使用的是NSNumber。在不更改实现的情况下,如何将数值声明为int(如果可能的话)?

为什么不能这样做:

if ([p1 respondsToSelector:@selector(moveAlongX:andY:)]) {
    [(id)p1 moveAlongX:1 andY:1];
}

顺便说一下,Cocoa命名约定会让您将此方法称为moveAlongX:y:

关于第二部分。如果你负责可能是p1类型的类,那么你可以用moveAlongBoth::定义protocol,而不是用performSelector检查conformsToProtocol。假设协议的名称是CanMoveAlong,那么您可以将其转换为

id <CanMoveAlong> canDo = (id<CanMoveAlong>)p1; 

在您检查一致性并直接调用方法之后

[canDo moveAlongX:1 andY:1];

这样一来,您就可以同时实现这两个功能,从而消除了警告,并且可以直接传递int,而无需使用NSNumber

最新更新