当在闭包方法swift上使用弱时,self会变为nil

时间:2019-07-20 12:07:55

标签: ios swift xcode closures

在我的关闭方法中,我必须解雇委托方法,但是由于weakSelf而没有解雇的委托变为nil。

import Foundation

protocol LoginViewModelDelegate: class {

func didCompleted(_ obj: LoginViewModel)
}

class LoginViewModel {

weak var delegate: LoginViewModelDelegate?
var schoolName: String

init() {
    schoolName = ""
}

func getSchoolNameFrom(schoolId: String) {
    weak var weakSelf = self
    LoginNetworkController.getSchoolName(schoolId) {[weak self] (result, status, message) in
         weakSelf?.schoolName = "Text"
         weakSelf?.delegate?.didCompleted(weakSelf!)

    }
}   

  }

1 个答案:

答案 0 :(得分:-1)

不要采用诸如weakSelf之类的局部变量。

LoginNetworkController.getSchoolName(schoolId) {[weak self] (result, status, message) in
    self?.schoolName = "Text"
    self?.delegate?.delegateMethoed(self!)
}

请检查是否让我知道这是否对您有用?