Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode Objective-C | iOS: delay function / NSTimer help?

So I'm developing my first iOS application and I need help..

Simple program for now, I have about 9 buttons and when I press the first button, or any button, I just want the first button to highlight for 60 milliseconds, unhighlight, second button highlights, wait 60 milliseconds, unhighlight and so on for the rest of the buttons so it looks like a moving LED.

I've looked tried sleep/usleep but once that sleep duration is done it seems like it skips the highlight/unhighlight all together.

For example:

- (void) button_circleBusy:(id)sender{
firstButton.enabled = NO;
sleep(1);
firstButton.enabled = YES;

and so on for the rest of the buttons. It DOES delay, but it doesn't delay the "firstButton.enabled = NO;". I have a picture for each button's "disabled state" and I never see it.

Any help's appreciated! I've looked into NSTimer but I was unsure on how to implement it.

Thanks.

-Paul

like image 891
Retro Avatar asked May 13 '11 23:05

Retro


4 Answers

sleep doesn't work because the display can only be updated after your main thread returns to the system. NSTimer is the way to go. To do this, you need to implement methods which will be called by the timer to change the buttons. An example:

- (void)button_circleBusy:(id)sender {     firstButton.enabled = NO;     // 60 milliseconds is .06 seconds     [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO]; } - (void)goToSecondButton:(id)sender {     firstButton.enabled = YES;     secondButton.enabled = NO;     [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToThirdButton:) userInfo:nil repeats:NO]; } ... 
like image 59
ughoavgfhw Avatar answered Oct 04 '22 12:10

ughoavgfhw


int64_t delayInSeconds = 0.6; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){      do something to the button(s) }); 
like image 40
Avner Barr Avatar answered Oct 04 '22 10:10

Avner Barr


Less code is better code.

[NSThread sleepForTimeInterval:0.06];

Swift:

Thread.sleep(forTimeInterval: 0.06)
like image 31
Alex Haas Avatar answered Oct 04 '22 11:10

Alex Haas


A slightly less verbose way is to use the performSelector: withObject: afterDelay: which sets up the NSTimer object for you and can be easily cancelled

So continuing with the previous example this would be

[self performSelector:@selector(goToSecondButton) withObject:nil afterDelay:.06];

More info in the doc

like image 42
Ramiro González Maciel Avatar answered Oct 04 '22 10:10

Ramiro González Maciel