如何在Objective-C中的特定时间后停止执行方法?

时间:2014-08-13 16:11:27

标签: ios objective-c multithreading

如何在iOS(Objective-C)下实现此逻辑?

  [obj method1]

  [OCRlib imageScan] // run <10 sec. or should be stopped.
                     // Display progress bar during execution.
                     // If does not finish in 10 seconds - stop it.
                     // OCRlib - third-party code I can't change

  [obj method2]      // wait imageScan results here

我在这里看到了Java / C#的答案,但没有看到Objective-C的答案。

1 个答案:

答案 0 :(得分:3)

我不确定如何停止imageScan方法,OCRlib是否提供了相应的方法?

要实现超时,您可以使用调度组

[obj method1]

dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, queue, ^{
    [OCRlib imageScan]
});

dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW,NSEC_PER_SEC * timeout);
long status = dispatch_group_wait(group, when );

if (status != 0) {
    // block completed
    [obj method2]
}
else {
    // block failed to complete in timeout
}