How to prevent crash on Cancel of MFMailComposeViewController?

前端 未结 2 1254
感动是毒
感动是毒 2021-01-01 02:14

Somewhere:

if([MFMailComposeViewController canSendMail])
{
    MFMailComposeViewController *email_vc = [[MFMailComposeViewController alloc] init];
    email_         


        
相关标签:
2条回答
  • 2021-01-01 02:26

    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.

    0 讨论(0)
  • 2021-01-01 02:27

    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];
    }
    

    }

    0 讨论(0)
提交回复
热议问题