MFMailComposeViewController在一个单独的类中

时间:2012-03-29 14:16:08

标签: iphone objective-c ios

我试图创建一个“实用程序电子邮件发件人类”,我可以在几个iPhone项目中使用它。

我为此目的创建了MailSender标头和实现。

MailSender.h:

@interface MailSender : NSObject<MFMailComposeViewControllerDelegate>

- (id) initWithParent:(UIViewController*) mainController;

- (void) invokeMailSender:(NSString*) to:(NSString*) subject:(NSString*) failureTitle:(NSString*) failureMessage:(NSString*) failureCancel;

@end

MailSender.m:

#import "MailSender.h"

@implementation MailSender

MFMailComposeViewController* mailer;
UIViewController* mailParentController;

- (id) initWithParent:(UIViewController*) mainController
{
    if( self = [super init])
    {
      mailParentController = mainController;
    }
    return self;
}

- (void) invokeMailSender:(NSString*) to:(NSString*) subject:(NSString*) failureTitle:(NSString*) failureMessage:(NSString*) failureCancel;

{
    if([MFMailComposeViewController canSendMail])
    {
        mailer = [[MFMailComposeViewController alloc] init];

        mailer.mailComposeDelegate = self;

        [mailer setSubject:subject];

        NSArray *toRecipients = [NSArray arrayWithObjects:to, nil];

        [mailer setToRecipients:toRecipients];
       [mailParentController presentModalViewController:mailer animated:YES];
    }
    else
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:failureTitle message:failureMessage
                                                       delegate:nil cancelButtonTitle:failureCancel otherButtonTitles: nil];

        [alert show];
    }
}

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    // Do nothing
    [mailParentController dismissModalViewControllerAnimated:YES];
    mailer = nil;
}



@end

我使用以下说明从视图控制器(按下触摸按钮操作)调用了该类:

@implementation InfoViewController

MailSender *sender;

- (IBAction)openMail:(id)sender
{
    sender = [[MailSender alloc] initWithParent:self];
    [sender invokeMailSender:@"test@test.com" :@"123" :@"123" :@"123" :@"123"];
}

.... 
@end

当我运行代码时,我能够正确显示电子邮件视图。然而,这之后是崩溃。 请注意,直接从我的UIViewController使用MFMailComposeViewController时我没有崩溃(并将View Controller指定为委托),

有什么想法吗? 对不起,我还是Objective C的新手:)

1 个答案:

答案 0 :(得分:7)

您需要保留发件人MailSender实例。它在您调用调用消息后被释放。

您可以通过声明名为property的{​​{1}}来执行此操作。 E.g。

sender

顺便说一下,你的方法声明有点搞笑。你应该命名参数。 E.g。

@property (strong, nonatomic) MailSender *sender;
...
@synthesize sender = _sender;
...
self.sender = [[MailSender alloc] initWithParent:self];
[self.sender invokeMailSender:@"noor@dimachk.com" :@"123" :@"123" :@"123" :@"123"];