将NSString写入文件 [英] write NSString to file
问题描述
我正在尝试将字符串写入文件,并将其存储在应用程序的applicationSupport文件夹中.但是我的NSLog()语句没有在调试器中记录任何内容.我已经尝试过使用调试器进行调试,我可以看到内容为nil,所以我猜测这就是为什么它不输出任何内容的原因,但是我不知道为什么将其设置为nil.有人可以看到我的错误吗?
I'm trying to write a string to a file and store that in the applicationSupport folder within my app. But my NSLog() statement doesn't log anything in the debugger. I have tried to go through it with the debugger, and i can see that the content is nil, so i'm guessing that's why it's not outputting anything, but i don't know why it's set to nil. Can anybody see my mistake?
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);
推荐答案
文件名
错误.它应具有以下格式:"directory/file.extension"
.您可以使用方法 stringByAppendingPathExtension
来构造这样的字符串.
filename
is wrong. It should have the following format: "directory/file.extension"
. You can use the methods stringByAppendingPathComponent
and stringByAppendingPathExtension
to construct such a string.
NSString *filename = [supportDirectory stringByAppendingPathComponent:[_nameTextField.text stringByAppendingPathExtension:@"txt"]];
此外,请注意,第一行应使用 stringWithFormat
重写,如下所示:
NSString *document = [NSString stringWithFormat:@"%@ %@ %@ %@ %@", description, focus, level, equipment, waterDepth];
这篇关于将NSString写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!