在Swift中使用UIAlertController进行内存泄漏 [英] Memory Leak using an UIAlertController in Swift
问题描述
我用这个简单的代码展示了一个简单的UIViewController
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)
}
当我按下界面上的按钮时,我将其称为IBAction并出现UIAlertController.但是,当我单击取消"按钮以关闭控制器时,泄漏工具发现了泄漏,如您在此图中看到的:
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
}))
但是总是有泄漏.
推荐答案
UIViewController
有很多陷阱.
Ash Furrow在此博客文章中解决了许多内存问题.他尝试了弱的self事情,但是决定使用一个局部变量,然后在闭包中使用该变量.
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.
这篇关于在Swift中使用UIAlertController进行内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!