views:

156

answers:

3

Hi guys,

How would I be able to use timers? For example I want to show a certain text for 10 seconds and then I want to show a different text for the rest of the duration.

Thanks,

Kevin

+2  A: 

Start with the Timer Programming Topics for Cocoa.

Rob Napier
+1  A: 

NSTimer documentation.

Mk12
+5  A: 

The easiest way to defer an action is to use NSObject's performSelector:withObject:afterDelay:

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

Set your text the first time (or at init time) and then do something like:

[self performSelector:@selector(changeText) withObject:nil afterDelay:10.0];

You can cancel the request with:

+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument

which you will need to do if you want your object to be deallocated as performSelector retains both your object and the withObject parameter.

Peter N Lewis
You have to do cancelPreviousPerformRequestWithTarget... ? I never have..
Mk12
The docs say that performSelector:withObject:afterDelay: retains the receiver and the withObject. So your object will not be deallocated until that selector is performed.
Peter N Lewis
+1 for posting code instead of saying RTFM.
willc2
But you don't have to cancel if the selector does get performed right?
Mk12
Correct. Essentially, the system retains both the receiver (self in this case) and the withObject, waits around 10 seconds, then invokes the method and releases the receiver and withObject. A consequence is that neither the receiver nor the withObject can be deallocated in the mean time.
Peter N Lewis