iosnsstream

iOS: App is hanging when trying to close the stream


I created NSStreams to transfer something using the below code:

dispatch_async(dispatch_get_main_queue(), ^{
    // open input
    [self.inputStream  setDelegate:controller];
    [self.inputStream  scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.inputStream  open];

    // open output
    [self.outputStream setDelegate:controller];
    [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.outputStream open];
});

At some point, I want to close the streams using the below code:

    // Shut down input
    [self.inputStream close];
    self.inputStream = nil;

    // Shut down output
    [self.outputStream close];
    self.outputStream = nil;

    NSLog(@"input streams status:%i", [self.inputStream streamStatus]);
    NSLog(@"output streams status:%i", [self.outputStream streamStatus]);
    NSLog(@"input streams status:%@", [self.inputStream streamError]);
    NSLog(@"output streams status:%@", [self.outputStream streamError]);

All input/output streams are strong properties.

Stream status return zero, but my app hangs. When I put device in debug mode, the monitor shows that my device CPU start running in 98+% after close method called. It seems like it's waiting for something to finish, but I still don't know what that is.

Does anyone know what may cause this issues?


Solution

  • Try removing the streams from the run loop.

    // Shut down input
    [self.inputStream close];
    [self.inputStream removeFromRunLoop: [NSRunLoop currentRunLoop] forMode: NSDefaultRunLoopMode];
    self.inputStream = nil;
    
    // Shut down output
    [self.outputStream close];
    [self.outputStream removeFromRunLoop: [NSRunLoop currentRunLoop] forMode: NSDefaultRunLoopMode];
    self.outputStream = nil;
    

    More information can be found here.