解决 Swift 中的循环依赖

God*_*her 5 swift

假设我有两个互相需要的课程。

class LoginInteractor {

     let userInteractor: UserInteractor

     init(userInteractor: UserInteractor) {
        self.userInteractor = userInteractor
     }

}

class  UserInteractor {
    let loginInteractor: LoginInteractor

    init(loginInteractor: LoginInteractor) {
        self.loginInteractor = loginInteractor
     }
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试这个( let loginInteractor = LoginInteractor() )我会得到循环依赖。我该如何解决这个问题?

rma*_*ddy 6

不能有两个类,其中两个类的初始值设定项都需要引用另一个类。这根本不可能。

您需要至少更改其中一个类以拥有不需要另一个类的初始值设定项。

那么你还会遇到一个问题,即双方都对对方有强烈的引用。这将导致引用循环(内存泄漏的一种形式)。因此,除了更改初始化程序之一之外,您还应该将引用之一设置为弱。

所以最后,您需要像任何其他父子类引用一样进行此操作。

在不了解更多信息的情况下,我建议更新UserInteractor为不需要LoginInteractor. 您可能有一个用户可以执行多项操作,登录只是一种可能的情况。

class UserInteractor {
    weak var loginInteractor: LoginInteractor?

    init() {
    }
}

class LoginInteractor {
     let userInteractor: UserInteractor {
         didSet {
             userInterator.loginInteractor = self
         }
     }

     init(userInteractor: UserInteractor) {
        self.userInteractor = userInteractor
     }
}
Run Code Online (Sandbox Code Playgroud)

通过此设置,您可以创建UserInteractor. LoginInteractor然后,您可以使用您的 实例创建 的实例UserInteractor

let userInteractor = UserInteractor()
let loginIteractor = LoginInteractor(userInteractor: userInteractor)
Run Code Online (Sandbox Code Playgroud)