writeToFile 不会更改文件的内容 xcode4 Objective-c

发布于 2024-12-02 09:35:31 字数 802 浏览 1 评论 0原文

我写完了一个小程序,它能够读取和写入 .txt 文件。 当我执行该程序时,除了文件内容不会永久更改之外,一切都运行良好。我有一个 writeToFile 和“readFile”按钮,每次按其中一个按钮时,内容似乎都会发生变化,但是当我手动打开文件时(在测试时或关闭程序后),其中仍然有原始内容。 仅使用模拟器时“真实”文件内容不会改变吗?或者只是我犯了一些严重的错误?

-(IBAction)buttonPressed {  //The writeToFile Method
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
NSString *writeData = enterText.text;
NSError *error;
BOOL ok = [writeData writeToFile:filePath atomically:NO encoding:NSUnicodeStringEncoding error:&error]; 
if (!ok)
{
    NSLog(@"Error while writing file at %@/n%@",filePath,[error localizedFailureReason]);
}
testText.text =@"File saved!";
enterText.text = @"";
enterText.placeholder =@"Enter your text here";

testText

= 用于输出的 TextView

EnterText = 用于输入的 TextField

I finished writing a little program, which is able to read and write a/into a .txt file.
When I execute the program, everything is running fine except that the content of the file doesn't change permanently. I got a writeToFile and "readFile" button and the content seems to change every time I press one of them, but when I open the file manually (while testing or after shutting down the program) theres still the origin content in it.
Doesn't the "real" file content change while just using the simulator? Or is it just me making some bad mistakes?

-(IBAction)buttonPressed {  //The writeToFile Method
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
NSString *writeData = enterText.text;
NSError *error;
BOOL ok = [writeData writeToFile:filePath atomically:NO encoding:NSUnicodeStringEncoding error:&error]; 
if (!ok)
{
    NSLog(@"Error while writing file at %@/n%@",filePath,[error localizedFailureReason]);
}
testText.text =@"File saved!";
enterText.text = @"";
enterText.placeholder =@"Enter your text here";

}

testText = TextView for Output

enterText = TextField for Input

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

就是爱搞怪 2024-12-09 09:35:31

您的 filePath 变量指向应用程序资源包中的一个文件(不可写)。您需要做的是找到用户的文档文件夹,并在其中创建文件。

Your filePath variable is pointing to a file within the resource bundle of your app (which is not writable). What you need to do is locate the user's Documents folder, and create your file there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文