Objective-C 中定时和重复线程执行
我想知道是否能够对重复执行的线程进行计时(例如在 NSTimer
中使用 scheduledTimerWithTimeInterval
方法时)。我有一个视图控制器,其中有一种方法我希望它可以手动(通过单击按钮)或自动(通过计时方法执行)执行。问题是,这个方法将与远程服务器连接,并且它将更新视图上的结果,所以我不希望它阻塞主线程(视图控制器线程)。
我不知道该用什么,所以如果有人知道怎么用,请告诉我:) 提前致谢..
I'm wondering if I'm able to time a thread to be executed repeatedly (like when using the scheduledTimerWithTimeInterval
method in NSTimer
).. I have a view controller, where there is a method I want it to be executed either manually (by clicking a button), or automatically (by timing the method execution). The problem is that, this method will connect with a remote server, and it will update the result on the view, so I don't want it to block the main thread (the view controller thread).
I don't know what to use, so if there's anyone knows how, please let me know :)
Thanks in advance..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您可能正在使用 NSURLConnection,如果是这种情况,那么正如 joshpaul 所说,默认情况下它将异步运行。也就是说,当您启动连接时,
NSURLConnection
对象将创建一个新线程,在该线程上执行其工作,并通过 委托方法,然后清理第二个线程。这意味着原始线程,无论是否是主线程,在连接工作时都不会被阻塞。那么,您所要做的就是让计时器的操作创建并运行连接。在其他情况下,您有多种选择。设置一个计时器方法非常容易,该方法将调用另一个在后台执行的方法:
这可能会使从另一个线程获取结果变得困难(因为您需要将对原始线程的引用传递给该方法) 。但是,由于您似乎一开始就在主线程上,因此可以使用
performSelectorOnMainThread:withObject:waitUntilDone:
为wait
传递NO
争论要回来。更复杂的选项是设置您自己的后台线程并在其上运行计时器,但如果这确实有必要,我会感到惊讶。
It sounds like you might be using an
NSURLConnection
, and if that's the case, then as joshpaul noted, it will act asynchronously by default. That is to say, when you start the connection, theNSURLConnection
object will create a new thread, do its work on that thread, and return results to you on the original thread via the delegate methods, cleaning up the second thread afterwards. This means that the original thread, main or not, will not be blocked while the connection does its work. All you have to do, then, is have your timer's action create and run the connection.In other cases, you have a couple of options. It's easy enough to set up a timer method that will call another method to be performed in the background:
This can make it difficult to get results back from the other thread (because you need to pass a reference to the original thread to the method). However, since you seem to be on the main thread to begin with, you can use
performSelectorOnMainThread:withObject:waitUntilDone:
passingNO
for thewait
argument to get back.The more complicated option is to set up your own background thread with a timer running on it, but I'd be surprised if that was really necessary.
如果您使用 NSURLConnection,它是异步的。这可能会满足您的需求。
If you're using NSURLConnection, it's asynchronous. That'll likely work for your needs.