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

前端 未结 7 1995
旧巷少年郎
旧巷少年郎 2021-02-01 15:32

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 wan

相关标签:
7条回答
  • 2021-02-01 15:45

    Less code is better code.

    [NSThread sleepForTimeInterval:0.06];
    

    Swift:

    Thread.sleep(forTimeInterval: 0.06)
    
    0 讨论(0)
  • 2021-02-01 15:48

    I would like to add a bit the answer by Avner Barr. When using int64, it appears that when we surpass the 1.0 value, the function seems to delay differently. So I think at this point, we should use NSTimeInterval.

    So, the final code is:

    NSTimeInterval delayInSeconds = 0.05;
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    
    //do your tasks here
    
    });
    
    0 讨论(0)
  • 2021-02-01 15:49

    Try

    NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.06 ];
    [NSThread sleepUntilDate:future];
    
    0 讨论(0)
  • 2021-02-01 15:50

    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];
    }
    ...
    
    0 讨论(0)
  • 2021-02-01 15:51

    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

    0 讨论(0)
  • 2021-02-01 15:52
    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)
    });
    
    0 讨论(0)
提交回复
热议问题