Q:

Can't access mapview on different class

I'm working on an iOS app and there's one small bug. My project contains the following:

Custom searchbar on top of a mapView (HomeViewController.swift)
View with a tableview which displays the searchresults (LocationSearchTable.swift)

When searching I add the view with the tableview on top of my mapview and behind my searchbar. This all works fine.
But now when I select a searchresult from the tableView it crashes because it says that my mapView is nil.
I'm having the following in HomeViewController.swift:
@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    mapView.delegate = self
}

Adding the LocationSearchTable to the mapView like this:
func didChangeSearchText(searchText: String) {
    if (searchText == "" ) {
        self.locationSearchTable.view.removeFromSuperview()
    } else {
        self.view.insertSubview(self.locationSearchTable.view, aboveSubview: mapView)
    }
}

And on the LocationSearchTable.swift I want to call the mapView when tapping on something in the list:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let mapView = HomeViewController().mapView
    print(mapView)
}

When trying to access the mapView from there it's nil. Why is that? And what am I missing here?
Kind regards,
Wouter

A:

You creating a new instance of HomeViewController and then asking for its mapView before the method awakeFromNib has occurred.  The mapView at that point will be nil until the HomeViewController controller is added to a screen
The best way to handle this if I'm reading your hierarchy right is to delegate back to the view with the map from you tableview.
Or you can pass a reference to mapView into The tableView

