在super.init中引用self

时间:2018-02-26 20:04:18

标签: swift closures swift4 initializer

我有以下代码(编辑:更新了代码,以便所有人都可以编译并查看):

import UIKit

struct Action
{
    let text: String
    let handler: (() -> Void)?
}

class AlertView : UIView
{
    init(actions: [Action]) {
        super.init(frame: .zero)

        for action in actions {
//            let actionButton = ActionButton(type: .custom)
//            actionButton.title = action.title
//            actionButton.handler = action.handler
//            addSubview(actionButton)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class TextAlertView : AlertView
{
    init() {
        super.init(actions: [
            Action(text: "No", handler: nil),
            Action(text: "Yes", handler: { [weak self] in
                //use self in here..
            })
        ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class MyViewController : UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let alert = TextAlertView()
        view.addSubview(alert)
        self.view = view
    }
}

每次我实例化TextAlertView时,它都会在访问权限不佳的super.init上崩溃。但是,如果我改变:

Action(title: "Yes", { [weak self] in
    //use self in here..
})

为:

Action(title: "Yes", {
    //Blank.. doesn't reference `self` in any way (weak, unowned, etc)
})

它有效!

在超级初始化过程中,有没有办法在动作块中引用self弱或不弱(在上面我是在super.init的参数中做的?

代码编译..它只是在运行时随机崩溃。

0 个答案:

没有答案