简体   繁体   中英

Constantly saving text from UITextview

In my iOS app I am trying to save the text of a UITextview to a file in the documents directory automatically as the UITextView is being edited. I have an NSTimer that calls the following void function repeatedly:

-(void)savetofile{
NSLog(@"Saving");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName = [[NSString alloc] initWithFormat:@"%@/%@.txt", documentsDirectory,myfilename];
    NSString *content = [[NSString alloc] initWithFormat:myText.text];
    [content writeToFile:fileName atomically:NO NSDocumentDirectoryingEncoding error:nil];        
}

When I run the app, I look at the debug console and it Says "Saving" once then then I get an EXC_BAD_ACCESS. What is going on?

First of all, I don't think you should be using a NSTimer, why don't you use the textview delegate to be notified on changes on your UITextView?

secondly, assuming "myText" is you UITextView, I would like you 1) to check if it really is a UITextView at this point of the code 2) to replace your

NSString *content = [[NSString alloc] initWithFormat:myText.text];

by a

NSString *content = [[NSString alloc] initWithString:myText.text];

Well, I don't really see what you need to create a new string for

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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