Here is some code that I’m trying to make save some UITextView text. When I run it and change the text and click the save button it works but when I take it from the multitasking bar it and open it back up, it crashes. Whats wrong?
- (NSString *)saveFilePath
{
NSLog(@"saveFilePath");
NSArray *path =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[path objectAtIndex:0] stringByAppendingPathComponent:@"savefile.plist"];
}
(The save file.plist is on my project file)
view did load
- (void)viewDidLoad
{
NSString *myPath = [self saveFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if (fileExists)
{
NSLog(@"file Exsists");
NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
notesTextView.text = [values objectAtIndex:0];
}
}
Save data button:
NSArray *values = [[NSArray alloc] initWithObjects:notesTextView.text, nil];
[values writeToFile:[self saveFilePath] atomically:YES];
Any help appreciated.
The only place in the code you’ve posted that could cause a crash is the line:
If the array is empty (has zero items in it) this will crash with an array out of bounds error. I suggest you put:
And see if your crash goes away.
In an unrelated note, you can actually simplify your code quite a bit by taking out the “if (fileExists)” part by just using [NSArray arrayWithContentsOfFile:…] which safely returns nil if the file doesn’t exist.