2012-07-28 126 views
2

我在iPhone应用程序中遇到了问题,其中某些应用程序运行时显示为正常的文件在应用程序重新启动时在某些情况下以0大小显示。我已经全面检查了我的代码。这些文件的编写方式基本上是:是保证iPhone上文件完整性所需的“synchronizeFile”吗?

NSFileHandle *fHandle = [NSFileHandle fileHandleForWritingAtPath: myFileName]; 
    do 
    { 
     // code to set value of myNSData 
     [fHandle writeData: myNSData]; 
     // some more logic here 
    } 
    while (!done) 

    [fHandle closeFile]; 

我已经看到无论是在模拟器和真实设备上的问题发生。它只是偶尔发生,所以情况很难追踪。

我的问题是:我是否需要调用[fHandle synchronizeFile]来确保数据进入永久存储?在我重新打开应用程序之前,iOS是否有可能从文件缓冲区中丢失数据,然后将其发送到永久存储器,从而导致文件大小为0的文件大小?

回答

1

我不确定写数据时的NSFileHandle结果,但我会建议使用NSData的writeToFile:atomically:方法,因为“原子”标志实现了你所要求的 - 它保证所有数据都被写入,或者没有。

+0

很好,但如果他需要一个TCP套接字的文件句柄呢?那么你用'writeToFile:'搞砸了。如果需要多个数据输出,我不会真的建议使用这个。 – 2012-07-28 18:17:47

+0

其实我需要写一个从多个地方获取数据的循环和writeToFile:在这种情况下,atomically不是一个选项。 – DDRider62 2012-07-28 23:10:57

+0

难题,那么文件句柄是必要的 – Stavash 2012-07-29 06:06:32

0

据我所知,它不需要被调用(也许除非你做了一些非常棘手的线程/ GCD /无论如何)。对我来说,简单地调用writeData:和closeFile就足够了。

1

按照docs,这是保证:

 
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. 

所以只要您拨打synchronizeFile,你可以肯定的是你写的所有内容被刷新。