我正在尝试将列表写入我项目中包含的文本文件(Deck.txt),相关代码如下:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Deck" ofType:@"txt"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
deck = [[NSString alloc]initWithFormat: @"%@\n%@ %@",file, txtQuantity.text, cardName];
//[deck writeToFile:filePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:nil];
[fileHandle writeData:[deck dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
当我运行代码时,它不会保存到文本文档中,或者至少不会保存到我的项目中。它仍将创建列表并从文件中读取我尝试写入的所有数据,但是当我关闭程序时,不会对文本文档进行任何更改。任何帮助都将非常感激。
答案 0 :(得分:16)
如果您已经拥有NSData实例,那么您当然可以将数据写入设备上的内置文档目录。通过一些搜索,从模拟器运行以查找目的并不难找到位置。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString *docFile = [docDir stringByAppendingPathComponent: @"deck.txt"];
//your variable "deck"
[deck writeToFile: docFile atomically: NO];
这肯定会写入文档目录中的文件。它应该只是改变你的代码从目录中读取。
答案 1 :(得分:2)
您无法写入捆绑路径中的文件。你想要NSDocumentDirectory。
答案 2 :(得分:2)
使用此设置文件路径(例如):
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/dt"];
然后存储这样的数据:
[VARNAME writeToFile:filePath atomically:YES (or NO)];
我认为你想做的事情可以更简单地完成。