0
votes

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!

2
Show the delegate being setup and calledWain
Does this code is inside the ViewController class or a sub viewController?Gal Marom
@GalMarom ViewController classManish Verma
Take a look at my answerGal Marom
Edit the question, don't add code in comments. Also, add context around the code, where is it, have you checked it was called...Wain

2 Answers

0
votes

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

0
votes

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!!