首页 > 解决方案 > 在 Objective-C 中的函数调用后等待特定时间

问题描述

我有一个函数调用,调用后我需要等待 5 秒钟。我不等待使用[NSThread sleepForTimeInterval:5]或简单sleep(5),因为它在主线程上运行,我最终会阻塞我的整个应用程序。

所需功能:

  1. 函数调用
  2. 睡5秒
  3. 继续处理其他功能

我如何在 Objective-C 上做到这一点?

标签: objective-ctimerthread-sleep

解决方案


dispatch_after 怎么样?

https://developer.apple.com/documentation/dispatch/1452876-dispatch_after

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    // throw your call to other functions in here
});

推荐阅读