代码之家  ›  专栏  ›  技术社区  ›  PaFi

UIAlertController中的内存泄漏关闭

  •  0
  • PaFi  · 技术社区  · 7 年前

    我在设置 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内存,这正常吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Renaud    7 年前

    它不是由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
      }