使用Xcode for iPhone dev将字符串写入文本文件

use*_*327 6 iphone xcode objective-c

我正在尝试将列表写入包含在我的项目(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];
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,它不会保存到文本文档中,或者至少不会保存到我的项目中.它仍将创建列表并从文件中读取我尝试写入的所有数据,但是当我关闭程序时,不会对文本文档进行任何更改.非常感激任何的帮助.

odd*_*ter 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];
Run Code Online (Sandbox Code Playgroud)

这肯定会写入文档目录中的文件.它应该只是改变你的代码从目录中读取.