UIViewController使用闭包时不释放

时间:2019-06-09 09:28:03

标签: ios swift closures

如果进程尚未完成,关闭Viewcontroller时,我将使用Alamofire来获取数据,但ViewController无法释放

func fetchingDataFromServer(url : String, completed:@escaping (Error?)->Void){

    Alamofire.request(url) .responseJSON {
        response in
        if let result = response.result.value as? [[String:String]]{
            if (response.error != nil){
                self.arrData = self.pasteData(result)
  //reload tableview data
                self.tbvData.reloadData()
                completed(response.error )
            }else{

            completed(nil)

            }


        }

    }
}

1 个答案:

答案 0 :(得分:0)

使用weak self参考

func fetchingDataFromServer(url : String, completed:@escaping (Error?)->Void){

    Alamofire.request(url) .responseJSON { [weak self] (response) in
        if let result = response.result.value as? [[String:String]]{
            if (response.error != nil){
               self?.arrData = self.pasteData(result)
               self?.tbvData.reloadData()
               completed(response.error)
            }else{
              completed(nil)
            }
        }

    }
}