UIAlertController memory leak/issues - Swift

半城伤御伤魂 提交于 2019-12-11 09:15:27

问题


Instruments shows a memory leak from simply opening and closing the alert controller.

@IBAction func delBtnAc(sender: AnyObject) {

    let deleteAlert = UIAlertController(title: "Delete Image?", message: "", preferredStyle: .Alert)

    let cancelIt = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)

    deleteAlert.addAction(cancelIt)
    presentViewController(deleteAlert, animated: true, completion: nil)
}

I have reduced the alert to only a cancel button for testing.

Edited: Removed deleteAlert.dismissViewController in closure. Fixed retain cycle, but still shows a memory leak. Perhaps a bug.


回答1:


Your alert action's completion handler has a strong reference to your alert controller.

Your alert action has a strong reference to its completion handler.

Your alert controller has a strong reference to the alert action.

So here we have a classic retain cycle.

The problem is the strong reference from the completion handler to the alert controller itself, which in this case, happens to be completely unnecessary. The alert controller dismisses itself after running the appropriate completion handler.

We can completely eliminate the line.

If we were doing something non-redundant in the completion handler, we would need to create a weak reference to the completion handler so that we could use that in the completion handler.



来源:https://stackoverflow.com/questions/31906856/uialertcontroller-memory-leak-issues-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!