NSThread参数问题

发布于 2024-12-05 09:05:21 字数 312 浏览 5 评论 0原文

[NSThread detachNewThreadSelector:@selector(addressLocation:) toTarget:self withObject:parameter];

[self addressLocation:parameter];

这两个语句应该做同样的事情吗?因为其中一个(第二个)给了我准确的结果,而另一个始终给我一个非洲海岸附近的随机位置。根据我的阅读,他们都应该做同样的事情;使用参数“parameter”执行addressLocation。唯一的区别是线程,但它正在访问全局易失性变量,所以这应该不重要,不是吗?

[NSThread detachNewThreadSelector:@selector(addressLocation:) toTarget:self withObject:parameter];

[self addressLocation:parameter];

Should these two statements do the same thing? Because one of them (the second one) gives me an accurate result, and the other consistently gives me a random location off the coast of Africa. From what I have read, they should both do the same thing; execute addressLocation with the argument 'parameter.' The only difference is the thread, but it is accessing a global volatile variable, so that shouldn't matter, should it?

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

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

发布评论

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

评论(1

一张白纸 2024-12-12 09:05:21

线程比这复杂得多。当您调用 detachNewThreadSelector 时,您正在创建一个新线程,但没有简单的方法可以让您知道该调用何时完成。它可以在调用线程中的下一行代码之前完成,也可以在几秒钟之后完成。

如果您先创建线程,则可以使用performSelector:onThread:withObject:waitUntilDone,并且您应该获得与使用[self addressLocation:parameter]相同的结果。但这不会给你带来很多好处,因为在你等待结果时你的主线程将什么也不做。

有很多方法可以从线程取回数据——例如,我喜欢从辅助线程调用performSelectorOnMainThread 将数据发送回主线程。

我会阅读 Grand Central Dispatch 看看它是否适合您的需求。

Threads are much more complicated than that. When you call detachNewThreadSelector, you are creating a new thread, but there's no simple way for you to know when that call completes. It could complete before the next line of code in the calling thread or many seconds later.

If you create the thread first, you can then use performSelector:onThread:withObject:waitUntilDone and you should get the same result as if you used [self addressLocation:parameter]. That won't do you a lot of good though because your main thread will be doing nothing while you wait for the result.

There are lots of ways to get data back from a thread -- I like to call performSelectorOnMainThread from the secondary thread to send the data back to the main thread, for example.

I would read up on Grand Central Dispatch to see if it suits your needs.

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