BAD_EXC_ACCESS 用于在释放时尝试加载视图控制器

BAD_EXC_ACCESS for attempting to load view controller while deallocating

我在线收到 BAD_EXC_ACCESS。原因是"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
                }
            }
        }
    }

performQuery "must be capable of running on any thread of the app" 的完成块(如文档中所述)。您调用 addOverlay 这是一个 UI 函数,并且在主队列上调用了很多。您需要将此方法分派到主队列。

旁注,与问题无关:for(var i = 0; i<records.count; i += 1) 写成 for record in records 更好。 C 风格语法已弃用。