Swift UIAlertController中的内存泄漏关闭

Swift UIAlertController中的内存泄漏关闭,swift,memory-leaks,protocols,uialertcontroller,Swift,Memory Leaks,Protocols,Uialertcontroller,我在设置UIAlertController时遇到内存泄漏,我看到其他线程在谈论UIAlertController中的内存泄漏。但是我不知道如何改变我的代码,这样内存泄漏就会消失。我将itemSelected从函数更改为计算属性,但它没有更改任何内容 protocol TriggerUIAlertController: class where Self: UIView { var itemsForPresenting: [String] { get } var t

我在设置UIAlertController时遇到内存泄漏,我看到其他线程在谈论UIAlertController中的内存泄漏。但是我不知道如何改变我的代码,这样内存泄漏就会消失。我将itemSelected从函数更改为计算属性,但它没有更改任何内容

 protocol TriggerUIAlertController: class where Self: UIView {
        var itemsForPresenting: [String] { get }
        var titleForCancel: String { get }
        var titleForAlertController: String { get }
        var itemSelected: Int? {get set}
    }

    extension TriggerUIAlertController {

         func triggerUIAlerController() {
            let alertList = UIAlertController(title: titleForAlertController, message: nil, preferredStyle: .actionSheet)
            let closure = { (alert: UIAlertAction!) -> Void in
                let index = alertList.actions.index(of: alert)
                guard index != nil else {
                    return
                }

                ///produces memory leak, idk why though -> has to be checked
                self.itemSelected = index!
            }
            for x in itemsForPresenting {
                alertList.addAction(UIAlertAction(title: x, style: .default, handler: closure))
            }
            self.window?.rootViewController?.present(alertList,animated: true, completion: nil)
            let cancelAction = UIAlertAction(title: titleForCancel, style: .cancel, handler: nil)
            alertList.addAction(cancelAction)
        }
    }

顺便说一句:仪器在使用大约五分钟后使用总共50gb的ram是正常的吗?

这不是由UIAlertController引起的泄漏,更一般地说是由保留周期引起的,您可以在每个包含对self的引用或在闭包外部创建的任何变量的闭包中使用它

您可以通过更改闭包的定义来避免它:

  let closure = { [weak self, weak alertList] (alert: UIAlertAction!) -> Void in
        guard let self = self, let alertList = alertList, let index = alertList.actions.index(of: alert) else { return }               
            self.itemSelected = index
您可以在此处找到更完整的解释:

代码审查:关闭的另一个实现可以是:

  let closure = { [weak self, weak alertList] alert in
        guard let self = self, let alertList = alertList, let index = alertList.actions.index(of: alert) else { 
            return
        }               
        self.itemSelected = index
  }

谢谢,我更改了代码,但仍然显示内存泄漏。。嗯,我的错误是,在alertList和关闭之间也可能有一个保留周期。我更正了代码。说到仪器内存使用-5gb是正常的,50太多了。