0

我有一个 NSThread,我想在一定时间后超时。

[NSThread detachNewThreadSelector:@selector(someFuntion) toTarget:self withObject:nil];

- (void) someFunction {
   //Some calculation that might take a long time.
   //if it takes more then 10 seconds i want it to end and display a error message
}

您可以提供的任何帮助将不胜感激。

谢谢,

Zen_silence

4

2 回答 2

2

不要使用 NSThread,而是使用 NSOperation。然后,您可以保留对该操作的引用,并将 NSTimer 设置为 10 秒。如果计时器触发,则告诉操作自行取消。

于 2010-03-18T21:47:43.627 回答
1

尝试这样的事情:

workerThread = [[NSThread alloc] initWithTarget:self selector:@selector(someFunction) object:nil];
[workerThread start];
timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:workerThread selector:@selector(cancel) userInfo:nil repeats:NO];

确保您 (1) 检查workerThread.isCancelled线程何时完成以查看线程是否超时,以及 (2)[timoutTimer invalidate]如果线程未超时,则调用以清理计时器。

于 2010-03-18T21:54:34.067 回答