更新UI时保留异步调用中的循环

时间:2017-10-01 13:08:35

标签: ios swift retain-cycle

以下是我使用的代码。使用此代码不会调用deinit,但是如果我注释掉这行,那么来自代码deinit的 weakSelf?.tableView.reloadData()就会被调用。我做错了吗?

ZLNetworkHelper.sharedManager.getUserSavedAddress { (response) in
        print("getUserSavedAddressFinished")
        ZLProgressIndicator.stopAnimation()
        if response.isSuccess && response.value != nil {

            weak var weakSelf = self
            guard weakSelf != nil else {
                return
            }

            weakSelf!.address = response.value!.sorted(by: {$0.isDefault && !$1.isDefault})
            weakSelf!.isExistingAddressSectionExpanded = false

            if weakSelf!.address.count == 0 {
                weakSelf!.title  = LocalizationUtility.RCLocalizedString("ADD_ADDRESS")
            }

            DispatchQueue.main.async {
                weakSelf!.tableView.reloadData()
            }
            if completion != nil {
                completion!(true)
            }
        }
        else {

            let message = response.error?.localizedDescription
            ZLCustomAlertVC.presentAlertInVC(self, withErrorMessage:message)
        }
    }

2 个答案:

答案 0 :(得分:1)

你想在闭包中捕捉弱自我:

getUserSavedAddress { [weak self] (response) in

当你稍后捕获它时,你仍然会在闭包中抓住对self的引用。

尝试这样的实现:

ZLNetworkHelper.sharedManager.getUserSavedAddress { [weak self] (response) in
    DispatchQueue.main.async {
        print("getUserSavedAddressFinished")
        ZLProgressIndicator.stopAnimation()
        if response.isSuccess && response.value != nil {


           self?.address = response.value!.sorted(by: {$0.isDefault && !$1.isDefault})
            self?.isExistingAddressSectionExpanded = false

            if self?.address.count == 0 {
                self?.title  = LocalizationUtility.RCLocalizedString("ADD_ADDRESS")
            }

                self?.tableView.reloadData()
            if completion != nil {
                completion!(true)
            }
        }
        else {

            let message = response.error?.localizedDescription
            ZLCustomAlertVC.presentAlertInVC(self, withErrorMessage:message)
        }
    }   
}

(我只在SO上更新了这个,所以你可能需要根据需要打开等等)

答案 1 :(得分:0)

您可以使用Fred Faust提供的代码,但也可以在您提供警报的其他部分使用weakself。