How to Wait in Objective-C

| | August 18, 2015

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) and finally changing the text to “Another text”.

But sleep(2) only freezes the app and “Another text” is set without displaying “A text” for 2 seconds.

How may I display “A text” for 2 seconds and then show “Another text”?

7 Responses to “How to Wait in Objective-C”

  1. Robert Yi Jiang on November 30, -0001 @ 12:00 AM

    I know I am late for this party. But I found people haven’t mention thread sleep. If you are using GCD to call that function. You can use :

    [NSThread sleepForTimeInterval:2.0f];   
    

    to delay the thread for 2 seconds.

    [self changeText: @"A text"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //Here your non-main thread.
            [NSThread sleepForTimeInterval:2.0f];   
            dispatch_async(dispatch_get_main_queue(), ^{
                //Here you returns to main thread.
                [self changeText: @"Another text"];
            });
        });
    

    Edit 2 (Feb 2015):

    I think the NSTimer is a great solution. My solution just given another option to achieve the goal of NSTimer.

    Please read: How do I use NSTimer?

    [NSTimer scheduledTimerWithTimeInterval:2.0
                                     target:self
                                   selector:@selector(doSomethingWhenTimeIsUp:)
                                   userInfo:nil
                                    repeats:NO];
    

    In the class, you need this method:

    - (void) doSomethingWhenTimeIsUp:(NSTimer*)t {
    
            // YES! Do something here!!
    
    }
    
  2. You can use

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

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

  3. Grand Central Dispatch has a helper function dispatch_after() for performing operations after a delay that can be quite helpful. You can specify the amount of time to wait before execution, and the dispatch_queue_t instance to run on. You can use dispatch_get_main_queue() to execute on the main (UI) thread.

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        // do something
    });
    
  4. You need to use a timer. Using sleep will halt your entire program. Check NSTimer

  5. 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.

  6. 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).

  7. George Johnston on November 30, -0001 @ 12:00 AM

    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
       }
    

Leave a Reply