Swift iOS : 解決了一個委託不工作的情況

RecoReco發表於2017-07-04

在解決一個遺產程式碼的過程中,我希望對UIAlertView稍作封裝,以便從巨大的ViewController內分離出特定的AlertView的程式碼,我這樣做的:

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow()
        window!.rootViewController = UIViewController()
        window!.rootViewController!.view.backgroundColor = .blue
        window!.makeKeyAndVisible()
        let a = AlertView()
        a.show()
        return true
    }
}
class AlertView : UIViewController,UIAlertViewDelegate{
    var done : ((_ buttonIndex: Int)->Void)?
    func show(){
        var createAccountErrorAlert: UIAlertView = UIAlertView()
        createAccountErrorAlert.delegate = self
        createAccountErrorAlert.title = "Oops"
        createAccountErrorAlert.message = "Could not create account!"
        createAccountErrorAlert.addButton(withTitle: "Dismiss")
        createAccountErrorAlert.addButton(withTitle: "Retry")
        createAccountErrorAlert.show()
    }
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){
            print("Why delegate of alert view does not work?")
    }
}複製程式碼

出乎意料的是,點選按鈕的時候,alertView:clickedButtonAt:就是不執行。然後很快問題解決,原因在於,AlertView例項是區域性的,程式碼執行後例項已經被釋放,委託也就跟著沒了。

解決方法很簡單,把:

let a = AlertView()複製程式碼

改成

    var a : AlertView
    ...
    a = AlertView()複製程式碼

即可。

相關文章