我有按钮的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];
}
我可以打开邮件编辑器,但在发送邮件时,保存草稿或删除草稿应用程序会崩溃。有什么想法吗?
答案 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];
}