Reputation:
I'm working on an iOS app and there's one small bug. My project contains the following:
HomeViewController.swift
)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
Upvotes: 2
Views: 261
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