iphone - 缓冲 NSOutputStream 用作 NSInputStream?

标签 iphone cocoa nsstream

我有一个消费者类,它采用 NSInputStream 作为参数,它将被异步处理,并且我想推送来自生产者类的数据,该生产者类要求它提供 NSOutputStream 作为其输出源。现在我如何设置一个缓冲(或透明)流作为生产者的输出流,同时作为我的消费者类的 NSInputStream?

我稍微研究了一下 NSOutputStream +outputStreamToMemory 和 +outputStreamToBuffer:capacity: 但还没有真正弄清楚如何将其用作 NSInputSource 的输入。

我有一些想法,设置一个保存实际缓冲区的中间人类,然后创建两个子类(每个 NSInput/OutputStream 一个),它保存对此缓冲类的引用,并让这些子类将大多数调用委托(delegate)给该类,例如输出子类方法 hasSpaceAvailable、write:maxLength:,对于输入,hasBytesAvailable、read:maxLength: 等。

任何有关如何处理这种情况的提示都将受到赞赏。谢谢。

最佳答案

实现此目的的一种方法是使用苹果开发人员网站上的示例代码。 SimpleURLConnection example

这是如何做到的,可以在 PostController.m 代码中看到

@interface NSStream (BoundPairAdditions)
+ (void)createBoundInputStream:(NSInputStream **)inputStreamPtr outputStream:(NSOutputStream **)outputStreamPtr bufferSize:(NSUInteger)bufferSize;
@end

@implementation NSStream (BoundPairAdditions)

+ (void)createBoundInputStream:(NSInputStream **)inputStreamPtr outputStream:(NSOutputStream **)outputStreamPtr bufferSize:(NSUInteger)bufferSize
{
    CFReadStreamRef     readStream;
    CFWriteStreamRef    writeStream;

    assert( (inputStreamPtr != NULL) || (outputStreamPtr != NULL) );

    readStream = NULL;
    writeStream = NULL;

    CFStreamCreateBoundPair(
        NULL, 
        ((inputStreamPtr  != nil) ? &readStream : NULL),
        ((outputStreamPtr != nil) ? &writeStream : NULL), 
        (CFIndex) bufferSize);

    if (inputStreamPtr != NULL) {
        *inputStreamPtr  = [NSMakeCollectable(readStream) autorelease];
    }
    if (outputStreamPtr != NULL) {
        *outputStreamPtr = [NSMakeCollectable(writeStream) autorelease];
    }
}
@end

基本上,您将两个流的末端与缓冲区连接在一起。

关于iphone - 缓冲 NSOutputStream 用作 NSInputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3221030/

相关文章:

IOS - 如何在后台运行应用程序?

ios - 如何解决 Objective C 中日期格式的问题

objective-c - 如何从 NSOpenPanel 读取 XML 文件的内容

swift - 在 Swift 中从 NSInputStream 接收数据

ios - NSNotificationCenter 无法将事件指示器设置为隐藏

iphone - UIImageView 中的圆角

iphone - 如果我使用 self.fooBar 而不是 fooBar,性能会有所不同吗?

支持 SSL/TLS 的 Objective-C TCP 服务器

swift - 将 Int 转换为 UnsafePointer<UInt8>

iphone - 为什么我无法通过 Interface Builder 将左栏按钮项添加到导航项?