我目前正在尝试将文本写入和读取目标 C 中的同一文件。
在我尝试写入捆绑的文本文件之前。从那以后,我了解到这是不可接受的。我知道在写入文件时存在权限问题。
我一开始就面临几个错误,主要是由于我对 Objective C 缺乏经验,尤其是 IO。当我尝试写入现有文本文件时,我应该将文件放在项目中的什么位置?目前我刚刚将文件拖放到我的项目中;我假设这是不正确的,这就是我的大部分问题的来源。
这是我编写文本文件的代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myFile.txt"];
NSFileHandle *filehandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[filehandle seekToEndOfFile];
[filehandle writeData:[@"Hello World" dataUsingEncoding:NSUTF8StringEncoding]];
调试后, elementfilePath
包含一个非常长的目录,甚至不在我的项目目录中。
这是我写入文件的代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"myFile.txt"];
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if (error)
NSLog(@"Error reading file: %@", error.localizedDescription);
myArray = [fileContents componentsSeparatedByString:@"\n"];
我知道文件的大部分来自文件所在的位置,我只是不知道放在哪里。如果可能,我还希望能够在应用程序关闭后物理打开并查看文件的内容。