user2023106
user2023106

Reputation:

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:

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

Upvotes: 2

Views: 261

Answers (1)

bolnad
bolnad

Reputation: 4583

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

Upvotes: 1

Related Questions