【问题标题】:Scheduled Time Delay [duplicate]预定时间延迟 [重复]
【发布时间】:2014-02-08 19:21:17
【问题描述】:

我正在尝试在我的代码中启动延迟,以便当操作到达代码的该部分时,只要安排了延迟,一切都会停止。我已经设置了时间延迟,这只是代码应该如何执行的问题。

这是我在项目中使用的时间延迟:

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

如你所见,这个 sn-p 输入了 5 秒的延迟。我遇到的问题是,当我使用此代码时,它并没有像我期望的那样做。以下是我正在尝试运行的功能:

- (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 秒,然后关闭警报。然而,这不会发生。相反,当我点击按钮时,first 有 5 秒的延迟,然后警报弹出并几乎立即自行消失。我已经用另一个 sn-p 代码尝试了这个时间延迟,反应相同。

CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();

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

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

我在这里做错了什么?为什么延迟会在警报弹出之前执行?

【问题讨论】:

  • 附带说明,像这样强制用户盯着警报视图一段时间会导致体验不佳,并且可能会在 HIG 中受到警告。
  • @joshcaswell 这不是我打算发布到 App Store 的应用程序,而是我将用于个人用途的应用程序。
  • @JoshCaswell 另一个问题是类似的,所以感谢您向我指出。我不知道它的存在。

标签: ios objective-c nsdate xcode5


【解决方案1】:

那是因为您正在休眠(并阻塞)应该从(主/UI 线程)呈现警报的线程。推荐你使用dispatch_after异步休眠,5秒后回调主线程解除alert。像这样的:

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];
});

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 2011-09-08
    • 2021-07-01
    相关资源
    最近更新 更多