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]?