2

我正在尝试将字符串写入文件并将其存储在我的应用程序的 applicationSupport 文件夹中。但是我的 NSLog() 语句没有在调试器中记录任何内容。我试图用调试器检查它,我可以看到内容是 nil,所以我猜这就是它不输出任何东西的原因,但我不知道为什么它设置为 nil。谁能看到我的错误?

 NSString *document = [[[[[[[[description stringByAppendingString:@" "]stringByAppendingString:focus]stringByAppendingString:@" "]stringByAppendingString:level]stringByAppendingString:@" "]stringByAppendingString:equipment]stringByAppendingString:@" "]stringByAppendingString:waterDepth];
//NSLog(@"%@", document);

//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *supportDirectory = [paths objectAtIndex:0];

//filename
NSString *filename = [NSString stringWithFormat:[_nameTextField.text stringByAppendingString:@".txt"], supportDirectory];

[document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];

NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:nil];
NSLog(@"%@", content);
4

3 回答 3

6

filename是错的。它应具有以下格式:"directory/file.extension". 您可以使用方法stringByAppendingPathComponentstringByAppendingPathExtension构造这样的字符串。

NSString *filename = [supportDirectory stringByAppendingPathComponent:[_nameTextField.text stringByAppendingPathExtension:@"txt"]];

另外,作为旁注,第一行应该这样重写stringWithFormat

NSString *document = [NSString stringWithFormat:@"%@ %@ %@ %@ %@", description, focus, level, equipment, waterDepth];
于 2012-04-27T14:48:57.417 回答
0

你有错误的初始化文件名​​。它应该是:

  NSString *filename = [NSString stringWithFormat:@"%@/%@", supportDirectory,[_nameTextField.text stringByAppendingString:@".txt"]];

它会起作用的!祝你好运:)

于 2012-04-27T15:09:12.873 回答
-4

NSString *filename = [NSString stringWithFormat:[_nameTextField.text stringByAppendingString:@".txt"], supportDirectory];

是错的。它应该是:

NSString *filename = [NSString stringWithFormat:"%@%@",[_nameTextField.text stringByAppendingString:@".txt"], supportDirectory];
于 2012-04-27T14:45:06.907 回答