在相同的NSThread中停止NSStream runloop

时间:2016-02-11 22:43:21

标签: multithreading nsthread nsstream nsrunloop

我正在尝试在项目的一个主题中运行NSStreams。我在下面创建了一个帖子:

self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(createStreams:) object:handler];
[self.thread start];

线程选择器实现很糟糕:

- (void)createStreams:(OpenStreamHandler)handler {

assert(![[NSThread currentThread] isMainThread]); // make sure this thread is not a main thread

// open input
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];

// open output
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream open];

[[NSRunLoop currentRunLoop] run]; // start a run loop, look at the next point }

现在我想删除在该线程中运行的流runloop,例如:

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

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

如何在不使用方法调配的情况下在正确的线程中运行上面的代码(右currentRunLoop)?

1 个答案:

答案 0 :(得分:0)

您可以使用 performSelector:onThread:withObject:waitUntilDone:

  - (void)closeStreams {
    // Shut down input
    [self.inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [self.inputStream close];
    self.inputStream = nil;

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

- (void)closeStreamsOnTread:(NSThread *)aThread {
    SEL selector = NSSelectorFromString(@"closeStreams");
    [self performSelector:selector onThread:aThread withObject:nil waitUntilDone:NO];
}