writeToFile 不会更改文件的内容 xcode4 Objective-c
我写完了一个小程序,它能够读取和写入 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 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.