ios writeToFile更改不保存

时间:2021-05-14 10:05:47

ios claims the file has been written to, but the changes never actually save, as if they remain in buffer. Do I have to flush or something?

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

- (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);
}

Output:

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

This is the output I get every time I run, so the changes don't actually get written to the file.

这是我每次运行时得到的输出,因此更改实际上不会写入文件。

Thanks for the help.

谢谢您的帮助。

3 个解决方案

#1


7  

You can't edit files in your main bundle. You have to first save the file to the applications documents folder then make any changes.

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

Here's some code to maybe fix your issue:

这里有一些代码可以解决您的问题:

First save the text to a directory you create:

首先将文本保存到您创建的目录:

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];

#2


0  

Use NO parameter

使用NO参数

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

iOS docs says

iOS文档说

(BOOL)useAuxiliaryFile
If YES, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the receiver is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

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

#3


0  

You can not write file on main bundle, because resource bundle are read only. You can also check return of writeToFile method. Which returns false if you deploy it on device.

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

#1


7  

You can't edit files in your main bundle. You have to first save the file to the applications documents folder then make any changes.

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

Here's some code to maybe fix your issue:

这里有一些代码可以解决您的问题:

First save the text to a directory you create:

首先将文本保存到您创建的目录:

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];

#2


0  

Use NO parameter

使用NO参数

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

iOS docs says

iOS文档说

(BOOL)useAuxiliaryFile
If YES, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the receiver is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

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

#3


0  

You can not write file on main bundle, because resource bundle are read only. You can also check return of writeToFile method. Which returns false if you deploy it on device.

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