How to Wait in Objective-C and Swift

后端 未结 8 807
自闭症患者
自闭症患者 2021-01-31 02:22

I want to change my UILabel\'s text after 2 seconds.

I tried setting my UILabel\'s text to \"A text\", and use sleep(2) a

相关标签:
8条回答
  • 2021-01-31 02:35

    You can use

    [self performSelector:@selector(changeText:) withObject:text afterDelay:2.0];
    

    or if you want to display it periodically, check the NSTimer class.

    0 讨论(0)
  • 2021-01-31 02:35

    You need to use a timer. Using sleep will halt your entire program. Check NSTimer

    0 讨论(0)
  • 2021-01-31 02:36

    You can use NSTimer, like so -

    [NSTimer scheduledTimerWithTimeInterval:0.5 
                                     target:self 
                                   selector:@selector(updateLabel:) 
                                   userInfo:nil 
                                    repeats:YES];
    

    Define another method updateLabel and do the updation there. Define your timeInterval to suite your needs...

    Also setting repeats to YES makes sure that this selector is executed every 0.5 seconds (in the above case).

    0 讨论(0)
  • 2021-01-31 02:50

    You can accomplish this with a timer, e.g.

       NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(eventToFire:) userInfo:nil repeats:YES]; // Fire every 4 seconds.
    
       ...
    
       - (void)eventToFire:(NSTimer*)timer {
          // Do Something
       }
    
    0 讨论(0)
  • 2021-01-31 02:50

    This is because the view isn't updated until the end of the runloop. Instead of using sleeps try using NSTimer to set a specific time to update the view.

    0 讨论(0)
  • 2021-01-31 02:53

    The follow method is good.

    You can replace your

    sleep(1);

    with

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC));

    0 讨论(0)
提交回复
热议问题