Search code examples
iosswiftuikituisearchcontroller

UISearchController's init(searchResultsController: UIViewController?) crashes


Calling UISearchController(searchResultsController: nil) in a new ViewController's viewDidLoad() crashes with EXC_BREAKPOINT (code=1, subcode=0x185d73080) (aka, some nil optional was unwrapped).

If I try to execute the code in another new project / playground, it works without crashing.

Having also created a custom UISearchController and having it debugged by breakpoints, it lead me to the init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) method and then it crashed. It might be linked.

I must mention that calling the simple init() does not crash my app.

Exact example:

override func viewDidLoad() {
    super.viewDidLoad()
    UISearchController(searchResultsController: nil)
}

Crash


Solution

  • Solved, but it's incredible. I created a new project and added files one by one to see which one interferes with my code.

    Seems like I had an extension:

        @IBInspectable var paddingRight: CGFloat {
        get {
            return rightView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            rightView = paddingView
            rightViewMode = .always
        }
    }
    

    And that rightView! crashed my app randomly without error.

    Lesson learned, extension can provoke that error.