我完成了一个小程序,它能够读取和写入.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
答案 0 :(得分:0)
您的filePath变量指向应用程序资源包中的文件(不可写)。您需要做的是找到用户的Documents文件夹,然后在那里创建文件。