缓冲用作NSInputStream的NSOutputStream?

cah*_*bin 14 iphone cocoa nsstream

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

我看了一下NSOutputStream + outputStreamToMemory和+ outputStreamToBuffer:capacity:但还没有真正弄清楚如何将它用作NSInputSource的输入.

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

任何有关如何处理这种情况的提示都表示赞赏.谢谢.

Jug*_*teR 11

实现此目的的一种方法是使用apple开发人员站点上的示例代码. SimpleURLConnection示例

这是如何做到的,如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
Run Code Online (Sandbox Code Playgroud)

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