2014-10-07 52 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