I have an application that connects to a server using NSStream in another thread. The application also closes the connection if the user decides to log out. The problem is that I can never successfully close a stream or stream when a user disconnects. The following is an example of my code, as I approach the creation of a stream for my network and try to close the stream:
+ (NSThread*)networkThread { static NSThread *networkThread = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ networkThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkThreadMain:) object:nil]; [networkThread start]; }); return networkThread; } + (void)networkThreadMain:(id)sender { while (YES) { @autoreleasepool { [[NSRunLoop currentRunLoop] run]; } } } - (void)scheduleInThread:(id)sender { [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [inputStream open]; } - (void)closeThread { [inputStream close]; [inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [inputStream release]; inputStream = nil; }
Call when trying to connect an input stream:
[self performSelector:@selector(scheduleInThread:) onThread:[[self class] networkThread] withObject:nil waitUntilDone:YES];
Any advice is appreciated.
source share