(iphone) how to setup runloop properly here? many questions
I've just started reading apple's thread programming guide.
I'm starting a thread and have a reference to itself.myThread = [[NSThread alloc] initWithTarget: self
selector: @selector(myThreadMain)
object: nil];
[self.myThread start];
and the threadMain looks like example code from the doc.
I'll need to change "exitNow" variable in the code from main thread to terminate this thread, but don't know how. myThreadMain loop needs to sleep when it's not performing any work, but also don't know how to implement it. The doc says i'll need at least one input source if the new thread won't die immediately, however the new thread needs only to receive "exit now message" and performSelector:onThread: call. Should I setup an input source?- (void) myThreadMain
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
BOOL exitNow = NO;
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
// Add the exitNow BOOL to the thread dictionary.
NSMutableDictionary* threadDict = [[NSThread currentThread] threadDictionary];
[threadDict setValue:[NSNumber numberWithBool:exitNow] forKey:@"ThreadShouldExitNow"];
// Install an input source.
// [self myInstallCustomInputSource];
while (!exitNow)
{
// Do one chunk of a larger body of work here. 开发者_运维百科
// Run the run loop but timeout immediately if the input source isn't waiting to fire.
[runLoop runUntilDate:[NSDate date]];
// Check to see if an input source handler changed the exitNow value.
exitNow = [[threadDict valueForKey:@"ThreadShouldExitNow"] boolValue];
}
[pool release];
}
I'm going to hand some jobs to this thread by
performSelector:onThread:withObject:
the selector to perform need to be defined as following,
but also don't know how to achieve this.- (void) selectorToPerformInThread
{
for( int i = 0; i < 10; ++i )
{
do something;
**if(received a new "selectorToPerformInThread" call
when we are still in this loop)
break out and let the new "selectorToPerformInThread"
in order to run from the beginning of loop**
}
}
That's a lot of questions...
Let me reiterate my questions.- How to set "exitNow" variable which is stored in threadDict.
- How to setup the thread so that it sleeps when no work(when it's not performing the selector) is needed.
- Should I set up an input source so that the thread doesn't die right away?
- How to setup run loop so that for every call to "performSelector", the same selector(if it's performing) is canceled, and run it from the beginning?
Thanks in advance.
1/ Either pass the exitNow variable by reference and set it in the threadDict or pass the object contains the variable and set obj.exitNow = YES;
2/ Just let it die when the thread finishes its job. You need a new thread, just start a new one
3/ I don't get your idea, sorry
4/ I think you need a singleton obj, and then you set the variable inside that object so that the thread exit and then you start a new thread and call the selector
精彩评论