Warning: performSelector may cause a leak because its selector is unknown

Complains about:
[someObject performSelector:NSSelectorFromString(@”someMethod”)];

Reason: with ARC the runtime needs to know what to do with the result of the method we are calling. The result can be anything: void, int, char, NSString, id etc. Usually this information is contained in header of the object type we are working with.
What ARC can do with the return value?

  • ignore non-object types (void, int etc)
  • retain object value, then release when it is not used anymore
  • do nothing, assume that return object value will be valid in local scope

The call to methodForSelector: assumes that the return value of the method is an object, but does not retain/release it. So, if the object is supposed to be released, there can be a memory leak.

What if return value is void?
From the compiler perspective it is still an object, so it gives us warning to prevent garbage pointer value being retained/released and crash of an app.

How to fix?

  • static selectors

[_controller performSelector:@selector(someMethod)];
here compiler is able to record all information about the object during compilation and doesn’t need to make assumptions

  • delay execution

[self performSelector:aSelector withObject:nil afterDelay:0.0];
used when acceptable (return object is void and there is no problem to let the runloop cycle once), removes warning by reassuring the compiler that no object can be returned and mismanaged

  • suppress warning

#pragma clang diagnostic ignored “-Warc-performSelector-leaks”
for one line, in case of the whole project macros can be used
Suppressing warnings is ambiguous and not welcomed by many programmers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s