0

I have a piece of network code that uses AsyncSocket but moves it to a separate runloop. I'm creating this runloop with the following piece of code:

[NSThread detachNewThreadSelector:@selector(_workerLoop) toTarget:self withObject:nil];

and here's how my _workerLoop looks like (they're both in the same class):

-(void)_workerLoop {
    workerLoop = [[NSRunLoop currentRunLoop] retain];

    while(keepWorkerLoopRunning) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        [workerLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.5f]];
        [pool release];
    }

    [workerLoop release];
    workerLoop = nil;
}

Now, according to the docs, the NSThread will retain the target, and as this thread will only terminate when AsyncSocket disconnects, it's impossible to release and deallocate this object until the socket disconnects.

How can I fix this or maybe I'm doing something wrong?

esad
  • 2,660
  • 1
  • 27
  • 23
  • so what is the problem? I assume since the thread runs the workerLoop which is part of the retained object you don't want to release it before the thread finishes. – stefanB Feb 17 '10 at 03:28
  • 2
    Do *not* use method names starting with underscores. Apple have stated that the underscore prefix is reserved for Apple only. – dreamlax Feb 17 '10 at 04:27
  • Why do you need to schedule it on a secondary thread? The name of the class says it's asynchronous; it's not like you're going to sit around blocked on it. The solution may simply be to schedule it on the main thread. You can use an operation queue or dispatch queue if you absolutely need to respond to incoming events on a thread; when something happens, enqueue an operation or block to handle it. – Peter Hosey Feb 17 '10 at 07:39
  • The reason I need the secondary loop is that while the main loop is processing the UI events (which in my app are going to be very frequent), the socket is blocked – esad Feb 17 '10 at 18:37

1 Answers1

0

I've solved this by refactoring the runloop constructor out into own class, referenced by parent class that handles the networking code. This way, parent object is being deallocated, it can stop the thread and release the runloop

esad
  • 2,660
  • 1
  • 27
  • 23