2016-11-09 92 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)