Get NSData from NSOutputStream in memory?

I want to use NSOutputStream to accumulate data, and then, when done, create an NSData object with the contents. I can do this when the output stream is file based, 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 to populate without creating a temp file. Can I do all this in my memory? I do not see the API for this in the NSOutputStream documentation.

+6
source share
1 answer

According to documents that are difficult to search, first initialize the output stream with memory, then call the propertyForKey method using the NSStreamDataWrittenToMemoryStreamKey key.

In your example:

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

Source: https://habr.com/ru/post/970008/


All Articles