- performSelector:withObject:
- performSelector:withObject:withObject:
Availability
Technology
- (id)performSelector:(SEL)aSelector;
aSelector
A selector identifying the message to send. The message should take no arguments. If a
is NULL
, an NSInvalid
is raised.
An object that is the result of the message.
The perform
method is equivalent to sending an a
message directly to the receiver. For example, the following messages all do the same thing:
The 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 NSObject
.
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.
- performSelector:withObject:
- performSelector:withObject:withObject: