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

标签 ios swift closures

我有一个自定义的 UIView Controller ,我是这样初始化的:

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)

可以将 Action 添加到与其中的 UIButtons 关联的 View Controller 。例如alert.addAction(NSLocalizedString("cancel", comment: ""), 样式: .cancel, actionBlock: nil

Action 是这样定义的结构:

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

Action 中的代码块在这个方法中处理:

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 创建 Action 时有一个选项,即自动关闭 View Controller 然后执行代码块。但是,如果 dismissAfterActionfalse,应用程序将因 malloc 错误 而崩溃。它并不总是崩溃,但如果我反复点击与该操作关联的按钮,它最终会崩溃。不确定这里发生了什么。有没有人遇到过这样的事情?好像是代码块的问题。

最佳答案

前段时间我可能遇到过问题。作为修复,您可以通过这种方式更改代码:

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

关于ios - 使用传递给函数的闭包会导致 malloc 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40435428/

相关文章:

swift - 快速测试节点是否附加到物理主体

ios - 在调用其他函数之前更新 UIView?

java - Java中的匿名类和闭包有什么区别?

ios - 如何使用 AirPlay 查找可用屏幕?

ios - 无法向 Azure 移动服务上的单个 iOS 用户发送推送通知

ios - 如何使用透明模式推送 View Controller ?

JavaScript:将参数传递给间接的匿名函数

ios - 如何让 iOS 设备以编程方式播放音乐?

带有自定义初始化器的 Swift 枚举丢失了 rawValue 初始化器

ios - AVPlayerLayer 在 UIView 层的位置