ios - UIAlertController 和内存使用

标签 ios swift memory-management swift3 uialertcontroller

我有一个非常简单的项目:只有一个 ViewController 和一个 UIButton。按钮的 IBAction 是:

var alertViewControllerTextField: UITextField?

var promptController = UIAlertController(title: "Type Something", message: nil, preferredStyle: .alert)

let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                print("\(alertViewControllerTextField?.text)")
            })

let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
                //promptController = nil
            }
            promptController.addAction(ok)
            promptController.addAction(cancel)
            promptController.addTextField { (textField) -> Void in
                alertViewControllerTextField = textField
            }
            self.present(promptController, animated: true, completion: nil)

当应用完成启动时,内存使用量为 14.4 Mb。

当我单击该按钮时,它达到 18.4 Mb(如果我一次又一次单击该按钮,它最终达到 20 Mb)。

不管怎样,我以为当我点击UIAlertController的cancelok按钮时,内存会回到14,4,甚至很慢,但事实并非如此。

我想使 UIAlertController 成为一个 optional 以便有机会在关闭时为它分配一个 nil,但是 UIAlertController 不能是 nil 因为你不能将它声明为可选的。我想让它成为一个成员并用 weak 关键字声明它(运气不好)。

那么,当我点击 UIAlertController 的其中一个按钮时,有什么方法可以减少内存使用量吗?

最佳答案

请将此代码放在 DispatchQueue 中,然后尝试通过此方法解决此问题

DispatchQueue.global(qos: .userInitiated).async
{
        self.present(promptController, animated: true, completion: nil)
}

关于ios - UIAlertController 和内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505601/

相关文章:

ios - 发送的 NSNotification 对象是(null)?

ios - 在 ios 中更改个人资料图片按钮

json - 在 Swift 中获取特定的 json 数据

c++ - 指针可以由等于 0 的随机地址初始化吗?

ios - 为什么 UILabel 会增加内存使用量?

objective-c - 如何正确释放 UITabController

ios - Swift UICollectionView 在点击时更新单元格标签而不是实时更新

ios - 如何正确使用DrawRect

ios - 我如何使用解析保存的数据来计算关注者的数量,如下所示:

json - 如何使用 Swift Decodable 协议(protocol)解析 JSON API 结构中的几个硬编码键?