How to prevent crash on Cancel of MFMailComposeViewController?

最后都变了- 提交于 2019-11-30 09:54:45

I guess the action sheet gets the dismiss message instead of the mail compose view controller.

Not quite.

The sequence of events probably happens like this:

  • Action sheet calls -actionSheet:clickedButtonAtIndex: on its delegate (the MFMCVC).
    • MFMailComposeViewController calls -mailComposeController:didFinishWithResult:error: on its delegate (your VC)
      • Your VC calls [self dismissModalViewControllerAnimated:NO]
        • This causes the MFMCVC to be released. Since the dismiss isn't animated, there is no longer anything referring to the MFMCVC. It gets dealloced!
  • Action sheet calls -actionSheet:didDismissWithButtonIndex: on its delegate
    • But its delegate has been dealloced!
      • So it crashes!

The fix would be for Apple to do actionSheet.delegate = nil in -dealloc.

A potential workaround

[[self.modalViewController retain] autorelease]
[self dismissModalViewControllerAnimated:NO]

This is a bit trickier to do if you are using ARC.

this works for me:

- (void) mailComposeController: (MFMailComposeViewController *) controller
       didFinishWithResult: (MFMailComposeResult) result
                     error: (NSError *) error {

if(result == MFMailComposeResultSent){
    [self dismissViewControllerAnimated:YES completion:NULL];
} else if (result == MFMailComposeResultCancelled) {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!