2015-06-22 99 views
1

我想實現一個類,它將從AppDelegate中提供一個MFMessageComposeViewController。類的聲明看起來是這樣的:MFMessageComposeViewControllerDelegate沒有被調用

import UIKit 
import MessageUI 

class MyClass: NSObject, MFMessageComposeViewControllerDelegate { 

    func sendAMessage() { 
     // message view controller 
     let messageVC = MFMessageComposeViewController() 
     messageVC.body = "Oh hai!" 
     messageVC.recipients = ["8675309"] 
     // set the delegate 
     messageVC.messageComposeDelegate = self 
     // present the message view controller 
     UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(messageVC, animated: true, completion: nil) 
    } 

    // delegate implementation 
    func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) { 
     switch result.value { 
     case MessageComposeResultCancelled.value: 
      controller.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) 
     case MessageComposeResultFailed.value: 
      controller.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) 
     case MessageComposeResultSent.value: 
      controller.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) 
     default: 
      break 
     } 
    } 
} 

在我的AppDelegate我創造和接受這樣一個推送通知後調用的MyClass一個實例:在精細第一

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { 
    // instance of class 
    let handler = MyClass() 
    // call method 
    handler.sendAMessage() 
} 

一切正常 - 消息視圖控制器出現並且沒有任何錯誤,但是無論何時按下發送或取消按鈕,消息視圖控制器都不會關閉,屏幕變得沒有響應,代理被調用而不是,並且我得到一個BAD_ACCESS錯誤。

如果我把MFMessageComposeViewControllerDelegate放在AppDelegate中,並設置了messageVC. messageVC.messageComposeDelegate = UIApplication.sharedApplication().delegate as! MFMessageComposeViewControllerDelegate,那麼一切正常,控制器按預期解除。

爲什麼MFMessageComposeViewControllerDelegate居住在MyClass對象中時不會被調用?感謝您的閱讀和幫助!

回答

2

它崩潰了,因爲您的handler對象在handler.sendMessage()的調用之後立即被釋放並釋放,然後嘗試發送或點擊取消時嘗試在該即時釋放對象上進行委託回調。該對象正在被釋放和釋放,因爲在application:didReceiveRemoteNotification:的結尾沒有任何內容被強制引用。

因爲要創建在您的應用程序委託這個對象,我建議讓您的應用程序委託財產守住這個對象:

var handler: MyClass? 

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { 
    // instance of class 
    handler = MyClass() 
    // call method 
    handler?.sendAMessage() 
} 
+0

是非常合情合理的,和它的工作就像一個魅力!謝謝 – gmh