在ios开发中将用户接受的输入写入文本文件

时间:2014-08-14 04:49:22

标签: ios file-io

我是ios开发的新手。我在将用户接受的输入写入文本文件时遇到了困难。右键我现在接受用户输入“警报”。但是现在我希望用户的输入直接写在文本文件中。是否可能?我该如何实现呢?

1 个答案:

答案 0 :(得分:0)

一旦我在SO中的某个地方找到它,它对我有用:

-(void) writeToTextFile{
        //documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        //create content - four lines of text
        NSString *content = @"One\nTwo\nThree\nFour\nFive";
        //save content to the documents directory
        [content writeToFile:fileName 
                         atomically:NO 
                               encoding:NSStringEncodingConversionAllowLossy 
                                      error:nil];

}

-(void) displayContent{
        //documents directory:
        NSArray *paths = NSSearchPathForDirectoriesInDomains
                        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                      documentsDirectory];
        NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];

}

修改

UIAlertView有一个名为clickedButtonAtIndex的委托方法。在您的控制器中实现此委托。然后从那里你可以得到文本。像:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"Save"]){
        NSString *yourText = [alertView textFieldAtIndex:0].text;
    }
    else if ([title isEqualToString:@"NO"]){

    }
}

请记住将AlertView委托添加到自己。

希望这会有所帮助.. :)