Hi all,
I was just recently futzing about with a sample application trying to get my head completely wrapped around NSRunLoop. The sample I wrote created a simple secondary thread via NSOperation. The secondary thread does a few tasks such as process an NSTimer and also some rudimentary streaming with NSStream. Both of these input sources require a properly configured NSRunLoop in order to execute.
My question is this. Originally I had some code that looked like this in the secondary thread:
NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop];
self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:connectTimeout
target:self
selector:@selector(connectionConnectedCheck:)
userInfo:nil
repeats:NO];
[myRunLoop addTimer:self.connectTimer forMode:NSDefaultRunLoopMode]; // added source here
[myRunLoop run];
[NSStream getStreamsToHostNamed:relayHost port:relayPort inputStream:&inputStream outputStream:&outputStream];
if ((inputStream != nil) && (outputStream != nil))
{
sendState = kSKPSMTPConnecting;
isSecure = NO;
[inputStream retain];
[outputStream retain];
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop: myRunLoop //[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[outputStream scheduleInRunLoop: myRunLoop //[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[inputStream open];
[outputStream open];
self.inputString = [NSMutableString string];
return YES;
}
Now, with the code above, the events would never process. Not on currentRunLoop. I did something terrible afterwards, as this was just an educational exercise, and modified it to run under NSRunLoop mainRunLoop. Worked like magic. However, I'm almost certain that depending on my main threads run loop in a secondary thread is on 10 different levels of wrong.
So my question is in two parts, and I hope that's OK.
What can possibly go wrong with the little 'hack' I applied in order to get the secondary thread to run and respond to events via the run loop?
What's the proper way to configure the secondary thread to listen to all events/timer based sources so I don't have to do step 1.
Thanks for the insight all.