I have a problem in an iPhone application where some files that appear to be fine when the app runs appear with 0 size on some occasions when the application restarts. I have checked my code all over. The way these files are written is basically :
NSFileHandle *fHandle = [NSFileHandle fileHandleForWritingAtPath: myFileName];
// code to set value of myNSData
[fHandle writeData: myNSData];
// some more logic here
I have seen the problem happen both in the simulator and on the real device. It only happens sporadically so the situation is hard to track.
My question is: Do I need to call [fHandle synchronizeFile] to make sure the data goes to permanent storage? Is there a chance that iOS will lose data from the file buffers before it is sent to permanent storage resulting in 0 size file when I reopen the app?
I'm not sure about the NSFileHandle result when writing data, but I would suggest using NSData's
writeToFile:atomically: method, as the "atomically" flag achieves just what you're asking about - it guarantees that either all data is written, or none is.
According to the docs, this is guaranteed:
synchronizeFile Causes all in-memory data and attributes of the file represented by the receiver to be written to permanent storage. - (void)synchronizeFile Discussion This method should be invoked by programs that require the file to always be in a known state. An invocation of this method does not return until memory is flushed.
So as long as you call
synchronizeFile, you can be sure that all content you have written is flushed.
As far as I know, it doesn't needed to be called (maybe unless you do some very tricky threading/GCD/whatever). For me, it's sufficient to simply call writeData: and closeFile.