UIAlertController中的内存泄漏关闭

时间:2018-12-13 12:14:44

标签: swift memory-leaks protocols uialertcontroller

设置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是正常的吗?

1 个答案:

答案 0 :(得分:1)

这不是由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

您可以在此处找到更完整的说明: Swift closures causing strong retain cycle with self

代码审查:闭包的另一种实现可以是:

  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
  }