2014-10-07 27 views
0

林界定符合UIAlertViewDelegate作爲這樣一類:UIAlertViewDelegate在單獨的類

class PaymentAlert: NSObject, UIAlertViewDelegate { 

    var orderId: Int! 
    var items: [String] 

    init(orderId: Int, items: [String]) { 
     self.orderId = orderId 
     self.items = items 
    } 

    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { 
     println(index) 
    } 

} 

然後,我在另一個類做這些動作:

var alertClass = PaymentAlert(orderId: orderId, items: items) 

       var alert = UIAlertView(title: "Payment declined", message: "Do you want to retry?", delegate: alertClass, cancelButtonTitle: "Cancel", otherButtonTitles: "Retry") 

       alert.show() 

,一切都會運行,除了中,clickedButtonIndex委託罰款函數永遠不會被調用,當我點擊任何按鈕,我試圖設置委託alertClass.self哪些沒有做太多。

爲什麼clickedButtonIndex函數永遠不會被調用?

回答

1

UIAlertViewdelegate屬性是weak因此您的PaymentAlert實例在點擊按鈕之前被銷燬。

您必須保持對PaymentAlert實例的強烈引用,直到警報解除爲止。

+0

你有任何保持強有力的參考的例子嗎? – 2014-10-07 20:32:04

+0

您正在嘗試構建的構造並不是那麼簡單。如果你在'UIViewController'內創建'UIAlertView',你應該在那裏存儲'PaymentAlert'到一個變量。 ----你也可以從'UIAlertView'繼承'PaymentAlert'並將自己設置爲'delegate'。 ----但總的來說,將單獨的警報類作爲您的委託並不是一個好習慣。顯示警報視圖的對象也應該是具有一致生命週期的委託。 – fluidsonic 2014-10-07 20:39:05