Buffering NSOutputStream used as NSInputStream?

前端 未结 4 928
花落未央
花落未央 2020-12-28 08:36

I have this consumer class that takes an NSInputStream as argument which will be processed async, and I want to push data that comes from a producer class that requires that

4条回答
  •  眼角桃花
    2020-12-28 08:54

    One way to accomplish this would be to use the example code on the apple developer site. SimpleURLConnection example

    This is how to do it, as can be seen in the PostController.m code

    @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
    

    Basically you attach the ends of two streams together with a buffer.

提交回复
热议问题