2

我还是 Objective C 语法的新手,所以我可能过于复杂了,但我似乎无法弄清楚如何将 NSTimeInterval 传递给线程。

我想启动一个从主线程发送的休眠 x 秒参数的线程,如下所示:

[NSThread detachNewThreadSelector:@selector(StartServerSynchThread) toTarget:self withObject:5];

- (void) StartServerSynchThread:(NSTimeInterval *)sleepSecondsInterval {

    [NSThread sleepForTimeInterval:sleepSecondsInterval];

}

但是编译器一直给我一个语法错误。我不确定应该怎么做。任何帮助,将不胜感激。谢谢!

4

2 回答 2

12

这与@Georg 的答案几乎完全相同,但使用了正确的类型。:)

如果您将 NSTimeInterval 放入NSNumber(的子类NSValue)中,则可以将其传入:

[NSThread detachNewThreadSelector:@selector(startServerSynchThread:) 
                         toTarget:self 
                       withObject:[NSNumber numberWithDouble:myTimeInterval]];

- (void) startServerSynchThread:(NSNumber *)interval {
  [NSThread sleepForTimeInterval:[interval doubleValue]];
}
于 2010-06-20T16:28:14.223 回答
2

object参数有类型,这id意味着只能传递类类型的对象。整数,比如5你试图传递的,以及NSTimeInterval(实际上只是一个typedeffor double),是基本类型,而不是类类型。

您可以NSNumber用作包装器或传递 aNSDate代替。

于 2010-06-20T16:06:08.103 回答