DDRider62
DDRider62

Reputation: 833

is "synchronizeFile" needed to guarantee file integrity on the iPhone?

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];
   do 
   {
        // code to set value of myNSData
        [fHandle writeData: myNSData];
        // some more logic here
   } 
   while (!done)

   [fHandle closeFile];

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?

Upvotes: 2

Views: 921

Answers (3)

Richard J. Ross III
Richard J. Ross III

Reputation: 55583

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.

Upvotes: 1

user529758
user529758

Reputation:

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.

Upvotes: 0

Stavash
Stavash

Reputation: 14304

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.

Upvotes: 1

Related Questions