3

My app runs a network task in a separate thread - it gets data from my server, processes it and displays the results on an ongoing basis. This works fine when I have only one such network connection in one thread. However, if I run a second thread with a similar network task, the second one works fine, but the first one stops responding. The code for my class that schedules the network processes is as follows. Any thoughts on what might be going wrong here?

NSThread * nThread;

- (NSThread *)networkThread {
    nThread = nil;

        nThread =
        [[NSThread alloc] initWithTarget:self
                                selector:@selector(networkThreadMain:)
                                  object:nil];
        [nThread start];

    DLog(@"thread: %@, debug description: %@", nThread, nThread.debugDescription);
    return nThread;
}


- (void)networkThreadMain:(id)unused {
    do {
            [[NSRunLoop currentRunLoop] run];
    } while (YES);
}

- (void)scheduleInCurrentThread:(id)unused
{
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                           forMode:NSRunLoopCommonModes];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                           forMode:NSRunLoopCommonModes];
}

-(BOOL) connectWithError:(NSString **) e
{
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"127.0.0.1", [server port], &readStream, &writeStream);
    inputStream = (__bridge NSInputStream *) readStream;
    outputStream = (__bridge NSOutputStream *) writeStream;

    [inputStream setDelegate:self];
    [outputStream setDelegate:self];

    [self performSelector:@selector(scheduleInCurrentThread:)
                 onThread:[self networkThread]
               withObject:nil
            waitUntilDone:YES];

    [inputStream open];
    [outputStream open];
}
R.S
  • 321
  • 3
  • 15
  • 1
    1. Do you use a second instance of this class to create the second connection? Otherwise the second connect would overwrite the instance variables `inputStream` and `outputStream`. - 2. Is `nThread` an instance variable of this class or just a local variable? – Martin R Oct 13 '12 at 08:38
  • yes, of course, I do use another instance of this class so inputSTream and outputStream are different objects. nThread is an instance variable. – R.S Oct 13 '12 at 17:30
  • vote up. Thanks for this post. Not the question but your code brings me forward. I was looking for this stuff since few weeks. – Watsche May 06 '14 at 08:03

0 Answers0