Memory Leak using an UIAlertController in Swift

不羁的心 提交于 2019-12-23 13:21:00

问题


I present a simple UIViewController using this simple code

@IBAction func addNewFeed(sender: UIBarButtonItem)
{

    var alertView: UIAlertController? = UIAlertController(title: NSLocalizedString("New Feed", comment: "Titolo popup creazione feed"),
        message: NSLocalizedString("Insert the Title and the Link for the new Feed.", comment: "Messaggio creazione nuovo feed"),
        preferredStyle: UIAlertControllerStyle.Alert)


    alertView!.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Annulla popup creazione nuovo feed"),
        style: UIAlertActionStyle.Cancel,
        handler: nil))

    presentViewController(alertView!, animated: true, completion: nil)

}

When i push a button on my interface i call this IBAction and UIAlertController appears. But when i click on Cancel button to dismiss the controller Leak Tool found a leak as you can see in this image:

I have tried putting a closure like this in handler parameter:

alertView!.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Annulla popup creazione nuovo feed"),
        style: UIAlertActionStyle.Cancel,
        handler: {[weak self] action in self!.dismissViewControllerAnimated(true, completion: nil)
        alertView = nil
        }))

but there's always that leak.


回答1:


UIViewControllerhas lots of traps to fall into.

Ash Furrow addresses many of the memory problems in this blog post. He tried the weak self thing, but settled on using a local variable that is then used in the closure.



来源:https://stackoverflow.com/questions/30666121/memory-leak-using-an-uialertcontroller-in-swift

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