Creating UIAlertController without presenting it p

2019-09-10 04:04发布

问题:

When creating a UIAlertController without presenting it, a warning is printed in the console. Why is this so?

override func viewDidLoad() {
    super.viewDidLoad()
    let _ = UIAlertController(title: "title", message: "message", preferredStyle: .Alert)
}

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior


Edit:

Is this warning safe to ignore? If the UIAlertController is already created and I decide to not present/use it what should I do?

回答1:

You are using _ (underscore) in your UIAlertController initilialisation. In Swift, using an underscore means the variable will not be used and in your case you are creating a UIAlertViewController and because of the underscore the ARC will probably deallocate it right away. Try replacing the _ with a variable name.



回答2:

Try to Write code in viewDidAppear it may solver your problem

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)
    let alertController = UIAlertController(title: "title", message: "message", preferredStyle: .Alert)
}