2016-11-09 93 views
1

我有一个非常简单的项目:只有一个ViewController和一个UIButton。该IBAction的按钮:UIAlertController和内存使用情况

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兆。

当我点击按钮达到18,4 Mb(如果我再次点击按钮,它终于达到20 Mb)。

无论如何,我想,当我点击UIAlertController的取消OK按钮,内存将返回至14.4,甚至慢,但这情况并非如此。

我想使UIAlertControlleroptional不得不为它分配在接近一个nil的机会,但UIAlertController不能nil因为你不能将它声明为可选。我想让它成为会员,并用weak关键字声明它(没有运气)。

那么,当单击UIAlertController的某个按钮时,是否有任何方法来减少内存使用量?

+0

这是在模拟器或设备? – jjatie

+0

它在模拟器中,没有在设备上试过 –

+2

在设备上尝试。模拟器中的内存使用不能提供准确的表示。 – jjatie

回答

0

请把DispatchQueue这个代码不是试图通过我这个

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

不,它是一样的 –

0

我见过其他地方,你需要声明alertViewControllerTextField弱,这样的操作不保留它解决了这个问题。 (不知道我还没有完全明白这一点。)

所以尝试:

var alertViewControllerTextField: UITextField? 

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

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

let cancel = UIAlertAction(title: "Cancel", style: .cancel) { [weak promptController] (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)