Reputation: 539
I have a UIViewController containing a MKMapView in Storyboard. Then I made an outlet of that mapview. From this screen I go to another screen where from a delegate is called back in the first viewcontroller which contains the map. Problem arises when in this delegate method, I try to get the mapview, it always gives me nil. Thus producing "unexpectedly found nil while unwrapping an Optional value”)" error.
Here is my code:
1)IBOutlet connection in MapViewController
@IBOutlet weak var map: MKMapView!
2) Delegate method in MapViewController:
func didSelectSearchContact(selectedContact: Contacts) -> Void{
let coordinate: CLLocationCoordinate2D = CLLocationCoordinate2DMake(selectedContact.lat, selectedContact.lng)
let span = MKCoordinateSpanMake(2.0, 2.0)
let region: MKCoordinateRegion = MKCoordinateRegion(center: coordinate, span: span)
print("self.map====== \(self.map)")
map.region = map.regionThatFits(region)//here comes the crash.
}
3) This is How the above delegate is being called from another view controller:
let contact = searchResults[indexPath.row] as! Contacts
self.delegate = MapViewController()
self.delegate?.didSelectSearchContact(contact)
Let me know what I'm doing wrong here!! Thanks!
Upvotes: 0
Views: 380
Reputation: 539
Finally, good 40 minutes to find out the error right in front of my eyes. :P
Problem was that I was trying to assign a new object of my controller when setting the delegate. Also, I was setting the delegate wrong way.
Now the step 3 (see my question) looks like this:
let contact = searchResults[indexPath.row] as! Contacts
//self.delegate = MapViewController // this line was the reason of error, so I commented it out
if (self.delegate != nil){
self.delegate?.didSelectSearchContact(contact)
}
Hope it helps someone else!!
Upvotes: 0
Reputation: 8629
So basically you hold a weak reference to the mapView. When you leave the ViewController to the new viewController the viewController is being deallocated. Therefore, it lost the pointer to the mapKit and retains it for the memory. I wouldn't recommend you to change it to a strong pointer but rather save necessary primitives or structures that you will need in the future. I.e when you operate the segue save the selectedContact.lat, selectedContact.lng or whatever you need.
I think you should have in your new ViewController a separate IBOutlet to the MAPKit that connects to the appropriate view. In your initialiser just set the mapView's params to focus on the required data
Upvotes: 0