Sends a specified message to the receiver and returns the result of the message.
- iOS 2.0+
- macOS 10.0+
- UIKit for Mac 13.0+Beta
- tvOS 9.0+
- watchOS 2.0+
- Objective-C Runtime
A selector identifying the message to send. The message should take no arguments. If
An object that is the result of the message.
perform method is equivalent to sending an
a message directly to the receiver. For example, the following messages all do the same thing:
perform method allows you to send messages that aren’t determined until run-time. This means that you can pass a variable selector as the argument:
But use caution when doing this. Different messages require different memory management strategies for their returned objects, and it might not be obvious which to use.
Usually the caller isn't responsible for the memory of a returned object, but that's not true when the selector is one of the creation methods, such as
copy. See Memory Management Policy in Advanced Memory Management Programming Guide for a description of ownership expectations. Depending on the structure of your code, it might not be clear which kind of selector you are using for any given invocation.
Due to this uncertainty, the compiler generates a warning if you supply a variable selector while using ARC to manage memory. Because it can't determine ownership of the returned object at compile-time, ARC makes the assumption that the caller does not need to take ownership, but this may not be true. The compiler warning alerts you to the potential for a memory leak.
To avoid the warning, if you know that
a has no return value, you might be able to use
perform or one of the related methods available in
For a more general solution, use
NSInvocation to construct a message that you can invoke with an arbitrary argument list and return value.
Alternatively, consider restructuring your code to use blocks as a means of passing chunks of functionality through an API. See Blocks Programming Topics for details.