views:

37

answers:

2

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?

A: 

I believe you should be checking the error object, not the success boolean value. After all - that's why you're passing it's address for the write operation.

if (error) {
     NSLog(@"Error: %@", err);
}

Also you may want to check that [textView text] does not return nil and if textView isn't nil itself.

Eimantas
+1  A: 

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;

Nikolai Ruhe
Thanks! It was a combination of a null text view, and an uninitialized NSError.
Khakionion