While I开发者_开发知识库 usually make use of NSOperation for having a thread do a short task/operation, I'd like to have a long-living dedicated thread that is always available to process certain operations. For this, I allocate a new NSThread and use the initWithTarget method:
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
My understanding is the selector passed in should be the thread's main method that is responsible for starting the runloop. What is the proper code to have in there?
Is a while loop like this appropriate...
(void)newThreadMainMethod {
while(1) {
[[NSThread currentThread] run];
}
}
or is there a more efficient way to do it so that the thread doesn't take up resources with a endless loop? I was thinking along the lines of having a timer wake up every 0.5 seconds and call run on the thread in case something new is available to work on. I would appreciate your input.
Thanks.
[[NSRunLoop currentRunLoop] run]
is what you want, but it will carry on forever so you only need to call it once (not in a loop). You can either:
- do that, terminating the thread from within the run loop when/if appropriate
- use
[[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: JIFFY_TIME]
, and poll for an exit condition in awhile()
loop like you've written.
精彩评论