开发者

Timing and repeating thread execution in Objective-C

开发者 https://www.devze.com 2023-03-04 19:11 出处:网络
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

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 kn开发者_StackOverflow中文版ows how, please let me know :) Thanks in advance..


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, the NSURLConnection 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:

- (void)periodicMethodTimerFire:(NSTimer *)tim {
    [self performSelectorInBackground:@selector(myPeriodicMethod:)
                           withObject:myPeriodicArgument];
}

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: passing NO for the wait 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.


If you're using NSURLConnection, it's asynchronous. That'll likely work for your needs.

0

精彩评论

暂无评论...
验证码 换一张
取 消