Steve
Steve

Reputation: 1153

BAD_EXC_ACCESS for attempting to load view controller while deallocating

I'm getting a BAD_EXC_ACCESS on line . The reason is "Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior".

func drawLocations(loc: CLLocation)
    {
        let center = CLLocationCoordinate2D(latitude: loc.coordinate.latitude, longitude: loc.coordinate.longitude)
        let lat: CLLocationDegrees = center.latitude
        let long: CLLocationDegrees = center.longitude
        var points = [CLLocationCoordinate2DMake(lat,long),CLLocationCoordinate2DMake(lat,long),CLLocationCoordinate2DMake(lat,long),CLLocationCoordinate2DMake(lat,long)]
        let polygon = MKPolygon(coordinates: &points, count: points.count)
        mapView.addOverlay(polygon)//where I get error
    }
func loadLocation(completion: (error:NSError?, records:[CKRecord]?) -> Void)
    {
        let query = CKQuery(recordType: "Location", predicate: NSPredicate(value: true))
        CKContainer.defaultContainer().publicCloudDatabase.performQuery(query, inZoneWithID: nil){
            (records, error) in
            if error != nil {
                print("error fetching locations: \(error)")
                completion(error: error, records: nil)
            } else {
                print("found locations: \(records)")
                print("found locations")
                completion(error: nil, records: records)
                guard let records = records else {
                    return
                }
                for(var i = 0; i<records.count; i += 1)
                {
                    self.drawLocations(records[i]["location"] as! CLLocation)//where I call function
                }
            }
        }
    }

Upvotes: 0

Views: 90

Answers (1)

Rob Napier
Rob Napier

Reputation: 299275

The completion block of performQuery "must be capable of running on any thread of the app" (as described in the docs). You call addOverlay which is a UI function, and so much be called on the main queue. You need to dispatch this method to the main queue.

Side note, unrelated to the question: for(var i = 0; i<records.count; i += 1) is much better written as for record in records. The C-style syntax is deprecated.

Upvotes: 1

Related Questions