Suppose I have a networking singleton that uses Alamofire's SessionManager such as this:
import Alamofire
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()
}
}
}
Which I then use in a service class:
class SomeService {
static let shared = SomeService()
private init() {}
func doSomePostRequest(params: [String: Any]? = nil, completion: (() -> ())? = nil) {
Network.shared.postRequest(params: params, completion: completion)
}
}
I then make a request and reload a tableview using this service class:
class MyViewController: UITableViewController {
@IBAction func fetchData(_: Any) {
SomeService.shared.doSomePostRequest {
// do i need to use [weak self] here?
self.tableView.reloadData()
}
}
}
Do I still need to use [weak self] to avoid crashes and strong reference cycles? At any point, the user can dismiss MyViewController by pressing Back.
Am I correct in assuming that I don't need it since the service class is a singleton? And that if I make it an instance in MyViewController, I'd have to use [weak self]?
You use weak references to objects to make sure they are deallocated when they should be.
A singleton never gets deallocated. Therefore, whether you have a strong, weak, or unsafe pointer doesn't matter. No need to make the reference weak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With