将已保存的电子邮件字符串添加到电

时间:2013-06-04 17:37:07

标签: ios objective-c cocoa-touch

为了在发送电子邮件时节省用户时间,用户会在首选项页面中保存电子邮件地址,该页面应在编写电子邮件时预先填写收件人。 (或者那就是我想要做的事情)这里是我卡住的地方,我如何将我保存的字符串用于对象以便预先填充收件人。

目前,该字符串不会预填充收件人

在偏好设置页面中保存:

NSString *savecontents = _emailAddress.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savecontents forKey:@"saveEmail"];
[defaults synchronize];

在邮件视图演示文稿中阅读

- (IBAction)email:(id)sender {

NSString *savedValue = [[NSUserDefaults standardUserDefaults] <---------- saved email string
                        stringForKey:@"saveEmail"];



if ([MFMailComposeViewController canSendMail]) {

    MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init]; 
    mail.mailComposeDelegate = self;

    NSArray *toRecipients = [NSArray arrayWithObject:savedValue]; <------- trying to get string here
    [mail setToRecipients:toRecipients];

    [mail setSubject:@"subject"];
    NSString *emailBody = [NSString stringWithFormat: @"text here"] ;
    [mail setMessageBody:emailBody isHTML:YES];

    mail.modalPresentationStyle = UIModalPresentationPageSheet;
    [self presentModalViewController:mail animated:YES];

}

到目前为止尝试过:

  NSArray *toRecipients = [NSString stringWithFormat:savedValue];
   [mail setToRecipients:toRecipients];

    NSArray *toRecipients = [NSString stringWithFormat:@"%@",savedValue];
   [mail setToRecipients:toRecipients];

谷歌,SO和敲打拳头

1 个答案:

答案 0 :(得分:1)

所有你需要的是:

if (savedValue.length) {
    [mail setToRecipients:@[ savedValue ]];
}

这使用现代的Objective-C数组语法。这与:

相同
if (savedValue.length) {
    NSArray *toRecipients = [NSArray arrayWithObject:saveValue];
    [mail setToRecipients:toRecipients];
}

您所拥有的代码正在尝试为NSString变量分配NSArray值。

另外,请不要使用stringWithFormat,除非您确实需要格式化字符串。