Mail Composer不会解雇iOS

时间:2015-01-22 12:46:26

标签: ios objective-c mfmailcomposeviewcontroller

我有按钮的ViewController,按钮上的操作:

        - (IBAction)clickMe:(id)sender {
            MailHelper *helper = [[MailHelper alloc] init];
            [helper setAllData:self];
        }

此外,还有邮件编写的助手类(MailHelper.h):

    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    #import <MessageUI/MessageUI.h>

    @interface MailHelper : UIViewController<MFMailComposeViewControllerDelegate>

    @property MFMailComposeViewController* mailView;
    - (void)setAllData:(UIViewController *)ctrl;

    @end

和实现(MailHelper.m):

- (void)setAllData:(UIViewController *)ctrl {

    mailView = [[MFMailComposeViewController alloc] init];
    mailView.mailComposeDelegate = self;

    mailView.toRecipients = @[@"mail@email.com"];
    [mailView setSubject:@"Subject"];

    [ctrl presentViewController:mailView animated:YES completion:nil];
}

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

    [self dismissViewControllerAnimated:YES completion:nil];
}

我可以打开邮件编辑器,但在发送邮件时,保存草稿或删除草稿应用程序会崩溃。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

MFMailComposeViewController被请求被驳回时,您正在self上调用解雇方法,但self正在提出te MFMailComposeViewController。 变化:

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

    [self dismissViewControllerAnimated:YES completion:nil];
}

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

    [controller dismissViewControllerAnimated:YES completion:nil];
}

要修复释放问题,请添加以下内容:

导入.m文件中的<objc/runtime.h>,并使self与传递的控制器相关联:

static void * MailHelperKey = &MailHelperKey;

- (void)setAllData:(UIViewController *)ctrl {
mailView = [[MFMailComposeViewController alloc] init];
mailView.mailComposeDelegate = self;

objc_setAssociatedObject(mailView, MailHelperKey, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
....
}


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

    [controller dismissViewControllerAnimated:YES completion:nil];
    objc_removeAssociatedObjects(controller);
}

这将确保只要呈现控件不会释放您的邮件助手。不值得美丽的价格,但应该工作。

答案 1 :(得分:1)

好的伙计们。解决方案是在其他地方制作助手的实例,让我们说:

@implementation ViewController
MailHelper *helper;

- (IBAction)clickMe:(id)sender {
    helper = [[MailHelper alloc] init];
    [helper setAllData:self];
}