Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 670
joseph.hainline Avatar asked May 28 '14 21:05

joseph.hainline


1 Answers

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];
like image 102
joseph.hainline Avatar answered Nov 09 '22 05:11

joseph.hainline