I\'m getting the following warning by the ARC compiler:
\"performSelector may cause a leak because its selector is unknown\".
Here\'s what
To make Scott Thompson's macro more generic:
// 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")
Then use it like this:
MYSilenceWarning(-Warc-performSelector-leaks,
[_target performSelector:_action withObject:self];
)
My guess about this is this: since the selector is unknown to the compiler, ARC cannot enforce proper memory management.
In fact, there are times when memory management is tied to the name of the method by a specific convention. Specifically, I am thinking of convenience constructors versus make methods; the former return by convention an autoreleased object; the latter a retained object. The convention is based on the names of the selector, so if the compiler does not know the selector, then it cannot enforce the proper memory management rule.
If this is correct, I think that you can safely use your code, provided you make sure that everything is ok as to memory management (e.g., that your methods do not return objects that they allocate).
As a workaround until the compiler allows overriding the warning, you can use the runtime
objc_msgSend(_controller, NSSelectorFromString(@"someMethod"));
instead of
[_controller performSelector:NSSelectorFromString(@"someMethod")];
You'll have to
#import <objc/message.h>
The compiler is warning about this for a reason. It's very rare that this warning should simply be ignored, and it's easy to work around. Here's how:
if (!_controller) { return; }
SEL selector = NSSelectorFromString(@"someMethod");
IMP imp = [_controller methodForSelector:selector];
void (*func)(id, SEL) = (void *)imp;
func(_controller, selector);
Or more tersely (though hard to read & without the guard):
SEL selector = NSSelectorFromString(@"someMethod");
((void (*)(id, SEL))[_controller methodForSelector:selector])(_controller, selector);
What's going on here is you're asking the controller for the C function pointer for the method corresponding to the controller. All NSObject
s respond to methodForSelector:
, but you can also use class_getMethodImplementation
in the Objective-C runtime (useful if you only have a protocol reference, like id<SomeProto>
). These function pointers are called IMP
s, and are simple typedef
ed function pointers (id (*IMP)(id, SEL, ...)
)1. This may be close to the actual method signature of the method, but will not always match exactly.
Once you have the IMP
, you need to cast it to a function pointer that includes all of the details that ARC needs (including the two implicit hidden arguments self
and _cmd
of every Objective-C method call). This is handled in the third line (the (void *)
on the right hand side simply tells the compiler that you know what you're doing and not to generate a warning since the pointer types don't match).
Finally, you call the function pointer2.
When the selector takes arguments or returns a value, you'll have to change things a bit:
SEL selector = NSSelectorFromString(@"processRegion:ofView:");
IMP imp = [_controller methodForSelector:selector];
CGRect (*func)(id, SEL, CGRect, UIView *) = (void *)imp;
CGRect result = _controller ?
func(_controller, selector, someRect, someView) : CGRectZero;
The reason for this warning is that with ARC, the runtime needs to know what to do with the result of the method you're calling. The result could be anything: void
, int
, char
, NSString *
, id
, etc. ARC normally gets this information from the header of the object type you're working with.3
There are really only 4 things that ARC would consider for the return value:4
void
, int
, etc)init
/ copy
family or attributed with ns_returns_retained
)ns_returns_autoreleased
)The call to methodForSelector:
assumes that the return value of the method it's calling is an object, but does not retain/release it. So you could end up creating a leak if your object is supposed to be released as in #3 above (that is, the method you're calling returns a new object).
For selectors you're trying to call that return void
or other non-objects, you could enable compiler features to ignore the warning, but it may be dangerous. I've seen Clang go through a few iterations of how it handles return values that aren't assigned to local variables. There's no reason that with ARC enabled that it can't retain and release the object value that's returned from methodForSelector:
even though you don't want to use it. From the compiler's perspective, it is an object after all. That means that if the method you're calling, someMethod
, is returning a non object (including void
), you could end up with a garbage pointer value being retained/released and crash.
One consideration is that this is the same warning will occur with performSelector:withObject:
and you could run into similar problems with not declaring how that method consumes parameters. ARC allows for declaring consumed parameters, and if the method consumes the parameter, you'll probably eventually send a message to a zombie and crash. There are ways to work around this with bridged casting, but really it'd be better to simply use the IMP
and function pointer methodology above. Since consumed parameters are rarely an issue, this isn't likely to come up.
Interestingly, the compiler will not complain about selectors declared statically:
[_controller performSelector:@selector(someMethod)];
The reason for this is because the compiler actually is able to record all of the information about the selector and the object during compilation. It doesn't need to make any assumptions about anything. (I checked this a year a so ago by looking at the source, but don't have a reference right now.)
In trying to think of a situation where suppression of this warning would be necessary and good code design, I'm coming up blank. Someone please share if they have had an experience where silencing this warning was necessary (and the above doesn't handle things properly).
It's possible to build up an NSMethodInvocation
to handle this as well, but doing so requires a lot more typing and is also slower, so there's little reason to do it.
When the performSelector:
family of methods was first added to Objective-C, ARC did not exist. While creating ARC, Apple decided that a warning should be generated for these methods as a way of guiding developers toward using other means to explicitly define how memory should be handled when sending arbitrary messages via a named selector. In Objective-C, developers are able to do this by using C style casts on raw function pointers.
With the introduction of Swift, Apple has documented the performSelector:
family of methods as "inherently unsafe" and they are not available to Swift.
Over time, we have seen this progression:
performSelector:
(manual memory management)performSelector:
performSelector:
and documents these methods as "inherently unsafe"The idea of sending messages based on a named selector is not, however, an "inherently unsafe" feature. This idea has been used successfully for a long time in Objective-C as well as many other programming languages.
1 All Objective-C methods have two hidden arguments, self
and _cmd
that are implicitly added when you call a method.
2 Calling a NULL
function is not safe in C. The guard used to check for the presence of the controller ensures that we have an object. We therefore know we'll get an IMP
from methodForSelector:
(though it may be _objc_msgForward
, entry into the message forwarding system). Basically, with the guard in place, we know we have a function to call.
3 Actually, it's possible for it to get the wrong info if declare you objects as id
and you're not importing all headers. You could end up with crashes in code that the compiler thinks is fine. This is very rare, but could happen. Usually you'll just get a warning that it doesn't know which of two method signatures to choose from.
4 See the ARC reference on retained return values and unretained return values for more details.
Strange but true: if acceptable (i.e. result is void and you don't mind letting the runloop cycle once), add a delay, even if this is zero:
[_controller performSelector:NSSelectorFromString(@"someMethod")
withObject:nil
afterDelay:0];
This removes the warning, presumably because it reassures the compiler that no object can be returned and somehow mismanaged.
@c-road provides the right link with problem description here. Below you can see my example, when performSelector causes a memory leak.
@interface Dummy : NSObject <NSCopying>
@end
@implementation Dummy
- (id)copyWithZone:(NSZone *)zone {
return [[Dummy alloc] init];
}
- (id)clone {
return [[Dummy alloc] init];
}
@end
void CopyDummy(Dummy *dummy) {
__unused Dummy *dummyClone = [dummy copy];
}
void CloneDummy(Dummy *dummy) {
__unused Dummy *dummyClone = [dummy clone];
}
void CopyDummyWithLeak(Dummy *dummy, SEL copySelector) {
__unused Dummy *dummyClone = [dummy performSelector:copySelector];
}
void CloneDummyWithoutLeak(Dummy *dummy, SEL cloneSelector) {
__unused Dummy *dummyClone = [dummy performSelector:cloneSelector];
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
Dummy *dummy = [[Dummy alloc] init];
for (;;) { @autoreleasepool {
//CopyDummy(dummy);
//CloneDummy(dummy);
//CloneDummyWithoutLeak(dummy, @selector(clone));
CopyDummyWithLeak(dummy, @selector(copy));
[NSThread sleepForTimeInterval:1];
}}
}
return 0;
}
The only method, which causes memory leak in my example is CopyDummyWithLeak. The reason is that ARC doesn't know, that copySelector returns retained object.
If you'll run Memory Leak Tool you can see the following picture: ...and there are no memory leaks in any other case: