使用传递给函数的闭包会导致malloc崩溃

时间:2016-11-05 06:27:59

标签: ios swift closures

我有一个自定义的UIView控制器,我最初是这样的:

inputPhoneNumberView.frame = CGRect(x: 0, y: 0, width: 286, height: 73)
let alert = SAAlertView(title: "Enter Your Phone Number", message: "Enter or update your phone number and we will send you a verification code via SMS.", customView: inputPhoneNumberView)
alert.addAction("Confirm", style: .default, dismissAfterAction: false, hasLoadingIndicator: true) { () -> Void in
    print("Hello!") //Testing code
}
alert.addAction(NSLocalizedString("cancel", comment: ""), style: .cancel, actionBlock: nil)
present(alert, animated: true, completion: nil)

可以将视图添加到与其中的UIButtons关联的视图控制器中。例如alert.addAction(NSLocalizedString("cancel", comment: ""), style: .cancel, actionBlock: nil

动作是如此定义的结构:

struct Action {
        var title: String
        var style: ActionStyle
        var actionBlock: (() -> Void)?
        var dismissAfterAction: Bool
        var hasLoadingIndicator: Bool
    }

操作中的代码块在此方法中处理:

fileprivate dynamic func doAction(_ sender: CustomButton) {

        // Make sure the action should be allowed for default only.

        let action = actions[sender.tag]

        guard sender.tag >= 0 && sender.tag < actions.count else {
            print("No action at that index.", logType: .Error)
            return
        }

        if let block = action.actionBlock {
            if action.dismissAfterAction {
                dismiss(animated: true, completion: { 
                    block()
                })
            } else {

                block() // The point the crash occurs!
            }
        } else {
            dismiss(animated: true, completion: nil)
        }
    }

dismissAfterAction创建操作时有一个选项,即自动关闭视图控制器然后执行代码块。但是,如果dismissAfterActionfalse,则应用会因malloc error而崩溃。它并不总是崩溃,但如果我反复点击与该动作相关的按钮,它最终会崩溃。不知道这里发生了什么。以前有人遇到过这样的事吗?似乎是代码块的问题。

1 个答案:

答案 0 :(得分:1)

前段时间我可能已经发过问题了。作为修复,您可以通过以下方式更改代码:

        //we already checked action block, so 
        action.actionBlock!()
        //block()  The point the crash occurs!