Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to use [weak self] if I'm making a network request using a singleton networking service?

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

like image 774
meowmeowmeow Avatar asked Jul 01 '18 09:07

meowmeowmeow


1 Answers

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.

like image 68
gnasher729 Avatar answered Oct 04 '22 16:10

gnasher729