views:

357

answers:

2

Trying to change a button pic, wait a second, then change back. Not having much luck trying to get that to work, so is there a way to just pause the program for a second, without having a timer actually executing anything, and without the program going on with the code?

+4  A: 

Try putting your change back code in a method, and call from your change method:

[self performSelector:@selector(changeBack:) withObject:nil afterDelay:1.0];
Paul Lynch
is there a way to pass that 2 objects for parameters of the selector? i found one with 2 withObject:'s but there's no after delay on that one.
marty
@marty: Add both objects to an NSArray and pass the NSArray as the object.
dreamlax
I prefer using a dictionary, as that can be expanded to any number of named arguments easily, with more readability/maintainability than an array.
Paul Lynch
A: 

You can call

// sleep first appeared in Version 7 UNIX, 1979
sleep(1);

Or, more modernly:

// usleep appeared in 4.3 BSD, released 1986
usleep(1000000);

Or, more modenly again:

// nanosleep can be found in POSIX.1b, published 1993
struct timespec ts;
ts.tv_sec = 1;
nanosleep(&ts, NULL);

Or, more modernly and more Cocoa-y:

// +sleepForTimeInterval first appeared in Mac OS X 10.5, 2007
[NSThread sleepForTimeInterval:1.0];

All of these will halt the current thread. If your application has only one thread then this means it will halt your entire application. It will be unresponsive to any user interface events for the duration of the sleep.

The NSObject reference shows a method called performSelector:withObject:afterDelay:. This method performs the selector after the specified delay by scheduling it in the run loop. This means that the run loop continues to loop around and process events, fire timers, drain the autorelease pool, send more scheduled messages and so on and so on.

In this particular case, it is probably better to schedule the selector in the run loop (provide the selector that changes the image back and provide a delay of a second).

dreamlax
Information was gathered from Mac OS X man pages.
dreamlax