Get NSData from an NSOutputStream in memory?
Asked Answered
C

1

8

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.

Clientele answered 28/5, 2014 at 21:29 Comment(0)
C
17

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];
Clientele answered 28/5, 2014 at 21:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.