Search code examples
objective-cuikitnsstringnslognserror

NSString fails, app crashes trying to NSLog the NSError


What it says on the tin. All I want to do is save an NSString to a .txt file in my Documents directory so it can be accessed by the user. This is called in applicationWillTerminate:

NSError* err;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"TheFile.txt"];
BOOL success = [[textView text] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err];
if (!success) {
     NSLog(@"Error: %@ %@", err, [err userInfo]);
}

In my case, success comes back as NO, and my app crashes (EXC_BAD_ACCESS) on the NSLog line. Any ideas?


Solution

  • If textView (or [textView text]) is nil, success will be NO but err will be uninitialized. That's the only possible way to crash here.

    Try setting NSError* err = nil;