我试图创建一个可以在多个iPhone项目中使用的“实用程序电子邮件发件人类”。
为此,我创建了MailSender header 和实现。
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
我使用以下说明从 View Controller (通过按钮按下操作)中调用了该类:
@implementation InfoViewController
MailSender *sender;
- (IBAction)openMail:(id)sender
{
sender = [[MailSender alloc] initWithParent:self];
[sender invokeMailSender:@"[email protected]" :@"123" :@"123" :@"123" :@"123"];
}
....
@end
运行代码时,我可以正确显示电子邮件 View 。但是,这之后将导致崩溃。
请注意,当直接从我的UIViewController使用MFMailComposeViewController时,我并没有崩溃(并且将View Controller分配为委托(delegate)),
有任何想法吗?
抱歉,我还是Objective C的新手:)
最佳答案
您需要保留发件人MailSender实例。调用调用消息后,它将被释放。
您可以通过声明一个名为property
的sender
来做到这一点。例如。
@property (strong, nonatomic) MailSender *sender;
...
@synthesize sender = _sender;
...
self.sender = [[MailSender alloc] initWithParent:self];
[self.sender invokeMailSender:@"[email protected]" :@"123" :@"123" :@"123" :@"123"];
顺便说一句,您的方法声明有点有趣。您应该命名参数。例如。
- (void)invokeMailSender:(NSString *)sender
to:(NSString *)to
subject:(NSString *)subject
failureTitle:(NSString *)failureTitle
failureMessage:(NSString *)failureMessage
failureCancelButtonTitle:(NSString *)failureCancelButtonTitle