gpt4 book ai didi

iphone - ios writeToFile 更改不保存

转载 作者:可可西里 更新时间:2023-11-01 17:10:24 34 4
gpt4 key购买 nike

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

输出:

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

这是我每次运行时得到的输出,所以更改实际上并没有写入文件。

感谢您的帮助。

最佳答案

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

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

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

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

关于iphone - ios writeToFile 更改不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10671017/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com