使用Swift时,应尽早释放Objective-C变量
我正在尝试使用mailcore2将Objective-c程序移植到Swift。该代码在Objective-C中运行良好,但MCOSMTP操作启动功能的关闭代码从未收到控制,且sendOperationWithData的解除锁定时间过早。看起来Start函数正在触发dealloc-不确定原因。这在Objective-C中不会发生使用Swift时,应尽早释放Objective-C变量,objective-c,swift,Objective C,Swift,我正在尝试使用mailcore2将Objective-c程序移植到Swift。该代码在Objective-C中运行良好,但MCOSMTP操作启动功能的关闭代码从未收到控制,且sendOperationWithData的解除锁定时间过早。看起来Start函数正在触发dealloc-不确定原因。这在Objective-C中不会发生 func sendEmailMessage() { var smtpSession:MCOSMTPSession = MCOSMTPSession()
func sendEmailMessage() {
var smtpSession:MCOSMTPSession = MCOSMTPSession()
smtpSession.hostname = "smtp.comcast.net";
smtpSession.port = 465;
smtpSession.username = usernamet";
smtpSession.password = "password";
smtpSession.connectionType = MCOConnectionType.TLS;
var builder:MCOMessageBuilder = MCOMessageBuilder();
var myto = ["to-emailt"]
builder.header.from = MCOAddress(mailbox: "from-email");
builder.header.to = myto;
builder.header.replyTo = ["reply-email"];
builder.header.subject = mySubject.text;
builder.htmlBody = myBody.text;
let rfc822Data:NSData = builder.data();
println("doing send")
var sendop:MCOSMTPSendOperation = smtpSession.sendOperationWithData(rfc822Data)
sendop.start({ (error: NSError!) -> Void
in
println("Message sent successfully")
})
}
}
sendop
在sendmailmessage()
返回时解除分配,因为不再有对它的强引用
您需要创建对它(属性)的强引用,或者将它存储在可以这样做的地方。如果mcosmtpOperation
是NSOperation
子类,则可以将其放入NSOperationQueue
中,而不是调用start()
。您还可以将其添加到数组中