Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/100.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios UIAlertViewDelegate在单独的类中_Ios_Swift - Fatal编程技术网

Ios UIAlertViewDelegate在单独的类中

Ios UIAlertViewDelegate在单独的类中,ios,swift,Ios,Swift,Im定义了一个符合UIAlertViewDelegate的类,如下所示: class PaymentAlert: NSObject, UIAlertViewDelegate { var orderId: Int! var items: [String] init(orderId: Int, items: [String]) { self.orderId = orderId self.items = items } fu

Im定义了一个符合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函数从未被调用?

UIAlertView
委托属性是
弱的
,因此您的
PaymentAlert
实例在点击按钮之前被销毁


您必须在某个地方保留对
PaymentAlert
实例的强引用,直到该警报被解除。

您有没有保留强引用的示例?您尝试构建的构造并不是那么简单。如果在
UIViewController
内创建
UIAlertView
,则应将
PaymentAlert
存储在变量中。---您还可以从
UIAlertView
中对
PaymentAlert
进行子类化,并将其自身设置为
delegate
--但一般来说,将单独的警报类作为代理不是一个好的做法。显示警报视图的对象也应该是具有一致生命周期的代理。