ios - 在 NSRunLoop 上调度流

标签 ios sockets nsrunloop nsinputstream nsoutputstream

我一直在关注这个教程http://www.raywenderlich.com/3932/networking-tutorial-for-ios-how-to-create-a-socket-based-iphone-app-and-server一切正常,但文本中有一行我不明白:

Our streams have to continuously be ready to send or receive data. To enable this we have to schedule the stream to receive events in a run loop. If we do not assign a run loop the delegate will block the execution of our code until there is no data on the stream to read or write, which is a case we want to avoid.

但是,如果我在代码中注释这些行:

//[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

一切都会正常进行。我真的不明白为什么我必须在主运行循环上安排这个?

在我看来,主线程上发生的所有事情都在这个运行循环中处理。因此,如果我按下按钮,它将在主运行循环中处理。在这里,如果我不在主运行循环中安排它,字节仍然会被接收和发送,所以对我来说这意味着它们在主运行循环中被处理。

最佳答案

您可以在任何您想要的运行循环中安排您的流。委托(delegate)的回调方法将在安排它的此类线程中调用。例如,我为我的 POSInputStreamLibrary 编写了一些单元测试,其中我的委托(delegate)在某个工作线程中接收事件。可以看到调度进程here

关于ios - 在 NSRunLoop 上调度流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27488906/

相关文章:

ios - 如何在 'Type to Siri'模式下调试Siri扩展?

ios - 如何在文本字段中允许和获取拟我表情贴纸

c++ - 使用 pthreads 重新排列数据包

ios - NSRunLoop cancelPerformSelectorsWithTarget 不工作

ios - 了解 NSRunLoop

ios - 如何检查 key 是否存储在 Swift 的 KeyChain 中

ios - NSURLSession 中的委托(delegate)和完成处理程序

Spring 数据 Redis : Connect via UNIX Sockets

java - Java 中的服务器程序并传递对 Socket 对象的引用

objective-c - NSRunLoop 结束时释放资源