解决Swift中的循环依赖

问题描述 投票:1回答:1

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

class LoginInteractor {

     let userInteractor: UserInteractor

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

}

class  UserInteractor {
    let loginInteractor: LoginInteractor

    init(loginInteractor: LoginInteractor) {
        self.loginInteractor = loginInteractor
     }
}

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

swift
1个回答
3
投票

你不能有两个类,其中两个的初始化程序都需要引用另一个。这根本不可能。

您需要更改至少一个类,以使初始化程序不需要另一个。

然后你也有一个问题,两个都有一个强引用另一个。这将导致参考周期(一种内存泄漏形式)。因此,除了更改其中一个初始化程序之外,还应使其中一个引用变弱。

所以最后,你需要像任何其他父子类引用一样。

不知道更多,我建议更新UserInteractor不要求LoginInteractor。您可能有一个用户执行多项操作,登录只是一种可能的情况。

class UserInteractor {
    weak var loginInteractor: LoginInteractor?

    init() {
    }
}

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

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

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

let userInteractor = UserInteractor()
let loginIteractor = LoginInteractor(userInteractor: userInteractor)
© www.soinside.com 2019 - 2024. All rights reserved.