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.

joseph.hainline
  • 24,829
  • 18
  • 53
  • 70

1 Answers1

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];
joseph.hainline
  • 24,829
  • 18
  • 53
  • 70