Search code examples
iosswiftnsexception

Terminating with uncaught exception of type NSException- Navigating to Another View Controller Programmatically


When I tap on the button, I want to bring up the Company Details view controller programmatically (using no storyboard), but I'm getting an NSException error for the button's function. I believe CompanyDetailsViewController() is null and I'm not sure why because I created a class called CompanyDetailsViewController

func detailsButtonTapped(sender: UIButton!) {
    let companyDetailsViewController = CompanyDetailsViewController()
    self.navigationController?.pushViewController(companyDetailsViewController, animated: true)
}

Company Details View Controller Class

import UIKit

class CompanyDetailsViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
 var tableView: UITableView  =   UITableView()
 let animals : [String] = ["Dogs","Cats","Mice"]

  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.blue
  }

  //code for create table view, etc
}

Solution

  • Solved! It was an error with the button's selector call because I didn't know the selector call was changed with Swift 3.

    class CompanyViewController: UIViewController {
        override func viewDidLoad() {
            button.addTarget(self, action: #selector(CompanyViewController.detailsButtonTapped(button:)), for: .touchUpInside)    
        }
    
    
        func detailsButtonTapped(button: UIButton!) {
            let companyDetailsViewController = CompanyDetailsViewController()
            self.navigationController?.pushViewController(companyDetailsViewController, animated: true)
        }
    }