如何将 NSTimeInterval 对象传递给 detachNewThreadSelector withObject 参数?

发布于 2024-09-06 04:42:04 字数 423 浏览 1 评论 0原文

我对 Objective C 语法仍然很陌生,所以我可能会让这个过于复杂,但我似乎无法弄清楚如何将 NSTimeInterval 传递给线程。

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

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

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

    [NSThread sleepForTimeInterval:sleepSecondsInterval];

}

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

I'm still new to Objective C syntax, so I might be overcomplicating this, but I can't seem to figure out how to pass an NSTimeInterval to a thread.

I want to initiate a thread that sleeps for x seconds parameter sent from main thread as follows:

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

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

    [NSThread sleepForTimeInterval:sleepSecondsInterval];

}

But the compiler keeps giving me a syntax error. I'm not sure exactly how it should be done. Any help would be appreciated. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

药祭#氼 2024-09-13 04:42:04

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

如果将 NSTimeInterval 装箱到 NSNumberNSValue 的子类)中,则可以将其传入:

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

- (void) startServerSynchThread:(NSNumber *)interval {
  [NSThread sleepForTimeInterval:[interval doubleValue]];
}

This is almost exactly the same as @Georg's answer, but using the proper types. :)

If you box the NSTimeInterval into an NSNumber (a subclass of NSValue), you can pass that in instead:

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

- (void) startServerSynchThread:(NSNumber *)interval {
  [NSThread sleepForTimeInterval:[interval doubleValue]];
}
对你而言 2024-09-13 04:42:04

object 参数为 id 类型,这意味着只能传递类类型的对象。整数,例如您尝试传递的 5 以及 NSTimeInterval (实际上只是 doubletypedef ) 是基本类型,而不是类类型。

您可以使用 NSNumber 作为包装器或传递 NSDate

The object parameter has id type, which means only class-type objects can be passed. Integers, like the 5 you are trying to pass, as well as NSTimeInterval (actually just a typedef for double), are fundamental types, not class-types.

You can use NSNumber as a wrapper or pass a NSDate instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文