There are a number of things that Cocoa provides by default that is really great.
If I wanted to call a method after X seconds in Java, I would have to create some sort of Timer class, create an Interface that defines a callback method, execute the timer with some class that implements the interface, have the Timer execute a timer loop handling all the necessary threading code (Thread Pool, etc).
With Cocoa you call performSelector:withObject:afterDelay:
performSelector:withObject:afterDelay:
Invokes a method of the receiver on the current thread using the default mode after a delay.
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
Parameters
- aSelector
A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.
See “Selectors” for a description of the
SELtype.- anArgument
The argument to pass to the method when it is invoked. Pass
nilif the method does not take an argument.- delay
The minimum time before which the message is sent. Specifying a delay of 0 does not necessarily cause the selector to be performed immediately. The selector is still queued on the thread’s run loop and performed as soon as possible.
Discussion
This method sets up a timer to perform the aSelector message on the current thread’s run loop. The timer is configured to run in the default mode (
NSDefaultRunLoopMode). When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in the default mode; otherwise, the timer waits until the run loop is in the default mode.If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the
performSelector:withObject:afterDelay:inModes:method instead. To ensure that the selector is performed on the main thread, use theperformSelectorOnMainThread:withObject:waitUntilDone:orperformSelectorOnMainThread:withObject:waitUntilDone:modes:method instead. To cancel a queued message, use thecancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.This method retains the receiver and the anArgument parameter until after the selector is performed.
Availability
- Available in Mac OS X v10.0 and later.
See Also
+ cancelPreviousPerformRequestsWithTarget:selector:object:– performSelectorOnMainThread:withObject:waitUntilDone:– performSelectorOnMainThread:withObject:waitUntilDone:modes:– performSelector:onThread:withObject:waitUntilDone:modes:Related Sample Code
Declared In
NSRunLoop.h
So, significant functionality is built into the main system allowing you to call an arbitrary Selector without any extra work.