如何在txt文件中编写iOS 7 [英] How to write in a txt-file, iOS 7
问题描述
我正在尝试制作适用于iOS 7的iPhone应用程序. 我已经在项目中创建了一个txt文件,并希望能够在按下写入"按钮时从txt文件写入文本,在按下读取"按钮时能够写入并读取数据,阅读.
I'm trying to make an iPhone app, for iOS 7. I've created a txt file in my project, and want to be able to write the text from the txt file, when I push the write-button, write, and be able to read data, when I push the read-button, read.
当我尝试读取数据时,我发现此方法有效:
I'v found this method working, when I try to read data:
- (IBAction)load:(id)sender {
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"text" ofType:@"txt"];
if (filePath) {
NSString *stringFromFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[TextView setText:stringFromFile];
}
}
在另一个按钮上,我希望它将数据写入项目中的txt文件. 我已经尝试了很多方法,但没有真正起作用-简单地说,它不会在文件中写入文本. 我找到了一种方法,该方法可以解决50%的问题.这意味着它无法保存我要写的文本,仅显示将文本放在文本框中.
On another button, I want it to write data to the txt file in my project. I've tried a lot of methods, but no of really works - it simple won't write text in the file. I've found one method, which works 50%. That means that it's not able to save the text I'm telling it to write, it only shows that it put's the text in the text box.
代码:
- (IBAction)write:(id)sender {
NSString *documentsDirectory = [NSHomeDirectory()
stringByAppendingPathComponent:@"Documents"];
NSString *filePath = [documentsDirectory
stringByAppendingPathComponent:@"text"];
//NSString *filePath = [[NSBundle mainBundle] pathForResource:@"text" ofType:@"txt"];
NSString *printString = [NSString stringWithFormat:@"The new text"];
[printString writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:nil];
if (filePath) {
NSString *stringFromFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[TextView setText:stringFromFile];
}
}
有人可以帮助我吗? 提前致谢! :)
Can any one please help me out? Thanks in advance! :)
推荐答案
您可以使用以下功能:
-(void) writeToTextFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = @"Your Desired Content";
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
这篇关于如何在txt文件中编写iOS 7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!