BAD_EXC_ACCESS用于在解除分配时尝试加载视图控制器

时间:2016-09-04 22:11:20

标签: ios swift view uiviewcontroller exc-bad-access

我正在线上获得BAD_EXC_ACCESS。原因是"在取消分配时尝试加载视图控制器的视图是不允许的,并且可能导致未定义的行为"。

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

1 个答案:

答案 0 :(得分:1)

performQuery&#34;的完成块必须能够在应用程序的任何线程上运行。 (如文档中所述)。你调用addOverlay这是一个UI函数,并且在主队列上调用了很多。您需要将此方法分派到主队列。

附注,与问题无关:for(var i = 0; i<records.count; i += 1)更好地写为for record in records。不推荐使用C风格的语法。