问题
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