在闭包内调用函数时的swift强链接

时间:2018-01-10 09:25:29

标签: swift closures

我对这段代码有疑问:

func sendDataToBackend()  {

    Alamofire.request(MoneyCupUsersBackEndRouter.sendBI(BudgetInsightConnectionData(budgetInsightResponse: (self.BudgetInsightJSON)!, budgetInsightPermanentToken: (self.permanentToken)!, srcDate: userData!.lastUpdatedAt))).validate().responseString
        { [weak self] response in

            switch response.result{
            case .success( _):
                DispatchQueue.main.async {
                    SVProgressHUD.dismiss()
                    _ = self?.navigationController?.popToRootViewController(animated: true)

                }

            case .failure(let error):
                self?.showError(title: "ERROR SENT DATA BACKEND", message: "Erreur lors de l'envoi des données au Backend", error: error)

            }
    }


}

func showError(title: String, message: String, error: Error) {
    print(title)
    print(error)
    DispatchQueue.main.async {
        SVProgressHUD.dismiss()
        let alert = UIAlertController(title: "erreur", message: message, preferredStyle:.actionSheet)
        alert.addAction(UIAlertAction(title: "OK", style: .default)
        { Void in
            _ = self.navigationController?.popToRootViewController(animated: true)}
        )
        self.present(alert, animated: true, completion: nil)
    }


}

在闭包中调用函数showError。但该功能还处理自我对象。由于在闭包内调用了showError,我是否通过调用创建了对self的强引用?如果是这样,我会解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您的代码没有问题,因为showError被捕获为弱,DispatchQueue.main.async闭包不会导致保留周期。