2012-05-20 70 views
3

ios声称文件已被写入,但更改从未实际保存,就好像它们保留在缓冲区中一样。我必须冲洗什么?ios writeToFile更改不保存

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSString *myFilePath = [[NSBundle mainBundle] 
          pathForResource:@"MyFile" 
          ofType:@"txt"]; 

    NSLog(@"\n\nPath = \n%@", myFilePath); 

    NSString *myFileContents = [NSString stringWithContentsOfFile:myFilePath 
            encoding:NSUTF8StringEncoding 
            error:nil]; 


    NSLog(@"\n\nContents = \n%@", myFileContents); 

    [@"This line will be written to file" writeToFile:myFilePath 
     atomically:YES encoding:NSUTF8StringEncoding error:nil]; 

    NSString *changedContents = [NSString stringWithContentsOfFile:myFilePath 
            encoding:NSUTF8StringEncoding 
            error:nil]; 

    NSLog(@"\n\nChanged Contents = \n%@", changedContents); 
} 

输出:

Path = 
/Users/hamzeh/Library/Application Support/iPhone Simulator/5.1/Applications/2B318687-A745-4CD9-85BA-52A01AB76F6E/savepersistentdata_tutorial.app/MyFile.txt 

Contents = 
This is a text file. 
The file will be displayed on the iPhone. 
That is all for now. 

Changed Contents = 
This line will be written to file 

这是输出每次都遇到我运行时间,所以变化不会真正得到写入文件。

感谢您的帮助。

+0

资源包是只读的。 –

回答

7

您无法编辑主包中的文件。您必须先将文件保存到应用程序文档文件夹,然后进行任何更改。

下面是一些代码来也许解决您的问题:

首先将文本保存到你创建一个目录:

NSString *myFilePath = [[NSBundle mainBundle] 
          pathForResource:@"MyFile" 
          ofType:@"txt"]; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); 
NSString *directory = [NSString stringWithFormat:@"%@/Some_Directory", [paths objectAtIndex:0]]; 

// Check if the directory already exists 
if (![[NSFileManager defaultManager] fileExistsAtPath:directory]) { 
    // Directory does not exist so create it 
    [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil]; 
} 

NSData *data = [[NSData dataWithContentsOfFile:myFilePath] retain]; 

NSString *filePath = [[directory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [myFilePath lastPathComponent]]] retain]; 



NSError *error = nil; 
if (![data writeToFile:filePath options:NSDataWritingFileProtectionNone error:&error]) { 
    [data writeToFile:filePath atomically:NO]; 
} 
[data release]; 
[filePath release]; 
+0

是的,我评论过我如何在下面修复它,主要的软件包文件是不可写的。 – peasant13337

0

使用NO参数

[@"This line will be written to file" writeToFile:myFilePath atomically:NO encoding:NSUTF8StringEncoding error:nil]; 

iOS的文档说

(BOOL)useAuxiliaryFile
如果是,接收器被写入到一个辅助文件,然后辅助文件重命名为路径。如果否,则接收器直接写入路径。 YES选项保证路径(如果存在的话)即使系统在写入期间崩溃也不会被破坏。

+0

这不适合我,但我想通了。而不是像我上面所做的那样获取文件路径,我通过:NSString * docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0]; NSString * path = [docsDirectory stringByAppendingPathComponent:@“MyFile.txt”]; – peasant13337

+0

哦..我错过了...是的,你只是在文档目录中写的,主要的软件包是只读的... –

0

你不能写在主束文件,因为资源包是只读的。您也可以检查退回writeToFile方法。如果将其部署到设备上,则返回false。