Is NSData streaming when saving or keeping the whole file content in memory when protecting a file?

Question!

I'm protecting a file on iOS 4.2 using NSData. The file has just been downloaded into a temp folder using a webservice and now I want to copy and protect it into its final destination using NSData and the following code:

NSData oData = NSData.FromFile ( sSourcePathAndFile );
NSError oError = null;
oData.Save ( sDestPathAndFile, NSDataWritingOptions.FileProtectionComplete, out oError );

What I'm wondering: if the file is now really huge, will NSData save it in chunks, or will it load the whole file to memory, run eventually out of memory, and fail?

Sidenote: if I backup my iOS device and restore to another device, will the protected files be readable there? If yes, the whole protection would not make a lot of sense to me.

By : Krumelur


Answers
From checking the monotouch documentation (though I'm no expert), NSData.FromFile appears to map exactly to the Objective-C:

NSData +dataWithContentsOfFile:

Causing the entire file to be loaded into memory at once. That's per this page — "A data object by reading every byte from the file specified by path", which is pretty much word for word with the relevant bit of Apple's NSData reference.

There doesn't appear to be a monotouch equivalent, but in Objective-C the correct thing to do would be to use:

NSData +dataWithContentsOfMappedFile:

As documented here.

iOS has a fully virtualised memory subsystem like every other OS, it just lacks a page file. When you use dataWithContentsOfMappedFile:, you map the file to main memory, causing the normal paging mechanisms to keep as much or as little of it in physical RAM as there is space to allow, like any other virtualised memory pool.

Though dataWithContentsOfMappedFile: may fall back on dataWithContentsOfFile: in some environments (though it shouldn't on iOS), the system can't substitute dataWithContentsOfMappedFile: for dataWithContentsOfFile: in all cases because the former requires that the file remain unchanged on disk for the duration of the NSData object's lifetime whereas the latter guarantees to read it all in immediately and to allow you to then delete or modify the original as you desire.

Hopefully somebody who is more of a monotouch expert can advise on how you could add NSData.FromMappedFile or on how this functionality is exposed through other means, if at all.

By : Tommy


If you want to control how much it buffers so that your device doesn't run out of memory, you can open up a FileStream (System.IO) and write the bytes manually. That's the great thing about MonoTouch. You can use the .NET framework.



This video can help you solving your question :)
By: admin