如果我使用单例网络服务发出网络请求,是否需要使用 [weak self]?

meo*_*eow 6 ios swift alamofire

假设我有一个使用 Alamofire 的 SessionManager 的网络单例,例如:

进口阿拉莫火

class Network {
    static let shared = Network()
    private init() {}

    private var sessionManager: SessionManager = {
        let configuration = URLSessionConfiguration.default
            configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders

                return SessionManager(configuration: configuration)
    }

    func postRequest(params: [String: Any]? = nil, completion: (() -> ())? = nil) {
        sessionManager.request(url, method: .post, parameters: params).validate().responseData {
            // do something with response
            completion()
        }?      }
}
Run Code Online (Sandbox Code Playgroud)

然后我在服务类中使用它:

class SomeService {
    static let shared = SomeService()
    private init() {}

    func doSomePostRequest(params: [String: Any]? = nil, completion: (() -> ())? = nil) {
        Network.shared.postRequest(params: params, completion: completion)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我发出一个请求并使用这个服务类重新加载一个表视图:

class MyViewController: UITableViewController {
    @IBAction func fetchData(_: Any)  {
        SomeService.shared.doSomePostRequest {
            // do i need to use [weak self] here?
            self.tableView.reloadData()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我是否仍然需要使用 [weak self] 来避免崩溃和强引用循环?在任何时候,用户都可以通过按 Back 关闭 MyViewController。

假设我不需要它,因为服务类是单身人士,我是否正确?如果我在 MyViewController 中让它成为一个实例,我就必须使用 [weak self]?

gna*_*729 4

您使用对对象的弱引用来确保它们在应该被释放的时候被释放。

单例永远不会被释放。因此,无论你有一个强、弱还是不安全的指针并不重要。无需使引用变弱。