Why do I get EXC_BAD_ACCESS right after instantiat

2019-07-29 18:48发布

问题:

I was reading this question and still can't figure out something. I placed breakpoints at AA & BB and saw that first AA happens which means destinationPlacemark gets instantiated. later at line BB I po destinationPlacemark and get error :

expression produced error: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x10). The process has been returned to the state before expression evaluation.

I read some of the answers found here but they are talking about a released object. How can that object be released as quickly as such?!

import UIKit
import CoreLocation

class ViewController: UIViewController {


var destinationPlacemark = CLPlacemark() //AA

override func viewDidLoad() {
    super.viewDidLoad() //BB
    forwardGeocoding(address: "1 Infinite Loop, Cupertino, CA 95014")
}
func forwardGeocoding(address: String) {
CLGeocoder().geocodeAddressString(address, completionHandler: { (placemarks, error) in
    if error != nil {
        print(error ?? "Error in plscement conversion")
        return
    }
    if (placemarks?.count)! > 0 {
        let placemark = placemarks?[0]
        let location = self.destinationPlacemark.location
        let coordinate = location?.coordinate
        print("Latitude: \(coordinate!.latitude), Longitude: \(coordinate!.longitude)")

        self.destinationPlacemark = placemark!
    }
})
}

}

回答1:

as explained in the answer in destinationPlacemark = CLPlacemark() was instantiated but has no location specified. Then location is being set to this nil. I posted the original question. Try chaning let location = self.destinationPlacemark.location to location = placemark.location