Scheduled Time Delay

I am trying to initiate a delay in my code, so when the action moves to this part of the code, everything stops while the delay is scheduled. I already set a time delay, it's just a question of how the code should be executed.

This is the time delay that I used in my project:

NSDate *timeDelay = [NSDate dateWithTimeIntervalSinceNow:5];
[NSThread sleepUntilDate:timeDelay];

As you can see, this snippet introduces a 5 second delay. The problem I am facing is that when I use this code, it does not do what I expect from it. The following is the function I'm trying to run:

- (IBAction)executeProgram
{
    UIAlertView *delayAlert = [[UIAlertView alloc]
                                initWithTitle:@"Delay"
                                message:@"This message follows with a 5 second delay."
                                delegate:nil
                                cancelButtonTitle:nil
                                otherButtonTitles:nil, nil];

    // Enable when time is working properly
    [delayAlert show];

    NSDate *timeDelay = [NSDate dateWithTimeIntervalSinceNow:5];
    [NSThread sleepUntilDate:timeDelay];

    // dismisses the alert
    [delayAlert dismissWithClickedButtonIndex:0 animated:YES];
}

, , , 5 , . . , , , 5 , . .

CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();

for (int x = 0; x<=5000; x++)
{
    NSLog(@"%i",x);
}

CFAbsoluteTime endTime = CFAbsoluteTimeGetCurrent();
CFAbsoluteTime elapsedTime = endTime - startTime;

? ?

+3
1

, ( ) , (/ ). dispatch_after , , 5 , . - :

UIAlertView *delayAlert = [[UIAlertView alloc]
                            initWithTitle:@"Delay"
                            message:@"This message follows with a 5 second delay."
                            delegate:nil
                            cancelButtonTitle:nil
                            otherButtonTitles:nil, nil];

[delayAlert show];

double delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [delayAlert dismissWithClickedButtonIndex:0 animated:YES];
});
+4

All Articles