UISearchController - Warning Attempting to load the view of a view controller

后端 未结 2 1356
别那么骄傲
别那么骄傲 2020-12-31 10:08

I am getting the following error.

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

2条回答
  •  孤城傲影
    2020-12-31 11:11

    The problem is a bug in UISearchController where it attempts to load its view in its dealloc method. Probably it calls self.view and the author has forgotten that self.view causes the view to be loaded. If the UISearchController has been created but hasn't been used then it doesn't load its view and this problem occurs. In your sample project if you tap in the SearchBar the warning doesn't appear.

    The solution is to force it to load its view. In your code there are two places you can do this: viewDidLoad() or deinit. Use one of the suggested lines (loadViewIfNeeded() or _ = .view) not both. If you're on iOS 9 only then probably best is to use the loadViewIfNeeded code in deinit. If you support iOS 8 then load the view manually as shown.

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tblSearchController = UISearchController(searchResultsController: nil)
        // etc. setup tblSearchController       
        self.tblSearchController.loadViewIfNeeded()    // iOS 9
        let _ = self.tblSearchController.view          // iOS 8
    }
    
    deinit {
        self.tblSearchController.loadViewIfNeeded()    // iOS 9
        let _ = self.tblSearchController.view          // iOS 8
    }
    

提交回复
热议问题