不允许在释放时尝试加载视图控制器的视图,这可能会导致未定义的行为

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior

我正在尝试实现发送邮件代码,但出现以下错误:

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior

这是我的代码片段:

    if MFMailComposeViewController.canSendMail() {
        let mail = MFMailComposeViewController()
        mail.mailComposeDelegate = self
        mail.setToRecipients(["@gmail.com"])            
        presentViewController(mail, animated: true, completion: nil)
    } else {
        // show failure alert
    }

我认为您的 "mail" 对象超出范围并在它出现之前被释放。

尝试在视图控制器的顶部制作 "mail" 一个 class 级变量:

    var mail: MFMailComposeViewController?

然后在您的按钮操作中设置和使用它:

    self.mail = MFMailComposeViewController()
    mail!.mailComposeDelegate = self
    //etc....

编辑:邮件对象由 presentViewController 函数保留,所以我的回答不正确。感谢张大牛指出这一点。

如果您忘记删除按钮的另一个功能的 segue,则可能会发生您收到的错误。