开发者

NSString fails, app crashes trying to NSLog the NSError

What it says on the tin. All I want t开发者_运维技巧o 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?


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜