我正在尝试将字符串写入文件并将其存储在我的应用程序的applicationSupport文件夹中。但是我的NSLog()语句没有在调试器中记录任何内容。我试图通过调试器进行检查,我可以看到内容为零,所以我猜测这就是为什么它不输出任何内容的原因,但是我不知道为什么将其设置为零。有人可以看到我的错误吗?
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);
最佳答案
filename
错误。它应该具有以下格式:"directory/file.extension"
。您可以使用 stringByAppendingPathComponent
和 stringByAppendingPathExtension
方法构造这样的字符串。
NSString *filename = [supportDirectory stringByAppendingPathComponent:[_nameTextField.text stringByAppendingPathExtension:@"txt"]];
另外,请注意,第一行应使用
stringWithFormat
重写,如下所示:NSString *document = [NSString stringWithFormat:@"%@ %@ %@ %@ %@", description, focus, level, equipment, waterDepth];
关于objective-c - 将NSString写入文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10352665/