iosfile-ionsdatansoutputstream

Get NSData from an NSOutputStream in memory?


I want to use an NSOutputStream to accumulate data, then when finished, create an NSData object with the contents. I can do it when the output stream is based on a file, as follows:

NSString *tmpDirectory = NSTemporaryDirectory();
NSString *filePath = [tmpDirectory stringByAppendingPathComponent:@"tempfile"];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
NSOutputStream *outputStream = [[NSOutputStream alloc] initToFileAtPath:filePath append:NO];     [outputStream open];

// fill the output stream here

NSData *contents = [NSData dataWithContentsOfFile:filePath];
[outputStream close];

I want the 'contents' variable filled without the temp file being created. Can I do this all in memory? I don't see API for that in the NSOutputStream documentation.


Solution

  • As per the hard to find documentation, first init the output stream with memory, then call the propertyForKey method with the key NSStreamDataWrittenToMemoryStreamKey.

    For your example:

    NSOutputStream *outputStream = [[NSOutputStream alloc] initToMemory];
    [outputStream open];
    
    // fill the output stream somehow
    
    NSData *contents = [outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
    [outputStream close];