How to save/load text files in Objective-C for the iPhone, using UITextView?

后端 未结 1 579
忘掉有多难
忘掉有多难 2020-12-21 02:11

How do you save text files permanently to an iPhone? And then be able to open them again in another UITextView?

Thanks in advance.

相关标签:
1条回答
  • 2020-12-21 02:41

    To write a NSString to a file:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];
    
    NSString *str = @"hello world";
    
    [str writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
    

    To load NSString from a file:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];
    NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
    

    And use text property of UITextView to set and get NSString.

    NSString *str = myTextView.text;
    myAnotherTextView.text = str;
    
    0 讨论(0)
提交回复
热议问题