简体   繁体   English

如何从文本字段读取用户输入的文本并将其写入Xcode中的文本文件?

[英]How can I read user input text from a textfield and write it to a text file in Xcode?

Is there a way to write a string , which is read from text field, to a .txt file? 有没有一种方法可以将从文本字段读取的字符串写入.txt文件?

NSString *input = [textfield text];

NSString *path = @"myText.txt";

[input writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];

Yes, ultimately that is the way; 是的,最终就是这样。 but there's a number of other steps you do in order to get from start to finish (you need to have textfield connected to an IBOutlet or in some other way accessible; the path where myText.txt is writing to needs to be writable and therefore you'd probably need to have a longer, more precise path than just the filename; you'd probably need to also send in an actual error parameter that could be set so you could look at the errors being returned when the writeToFile call fails the first few times you run this code). 但是要从头到尾完成还有许多其他步骤(您需要将文本字段连接到IBOutlet或以其他某种方式可访问; myText.txt写入的路径需要可写,因此您可能需要的路径不仅仅是文件名,而且路径更长,更精确;您可能还需要发送一个可以设置的实际错误参数,以便您可以查看当writeToFile调用第一次失败时返回的错误。几次运行此代码)。

You will need to define a path, basically where to save the file. 您将需要定义路径,基本上是保存文件的位置。 This code will find the Documents folder 此代码将找到Documents文件夹

NSArray *path = NSSearchPathForDirectoriesInDomains( 
            NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentDirPath = [path objectAtIndex:0]; 

Here is the code I use to read and write files. 这是我用来读写文件的代码。

-(void)writeFileToDisk:(id)data 
{ 
    NSArray *path = NSSearchPathForDirectoriesInDomains( 
            NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentDirPath = [path objectAtIndex:0]; 
    NSString *fileName = @"MyFileName.txt"; 

    NSString *fileAndPath = [documentDirPath stringByAppendingPathComponent:fileName]; 

    [data writeToFile:fileAndPath atomically:YES]; 
} 

-(void)readFileFromDisk 
{ 
    NSArray *path = NSSearchPathForDirectoriesInDomains( 
            NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentDirPath = [path objectAtIndex:0]; 
    NSString *fileName = @"MyFileName.txt"; 

    NSString *fileAndPath = [documentDirPath stringByAppendingPathComponent:fileName]; 

    NSArray *array = [[NSArray alloc] initWithContentsOfFile:fileAndPath]; 
    NSLog(@"%@",array); 
    [array release]; 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM