weak self be used in DispatchQueue

582 views Asked by At

Here is a simple API class as shown below.

class API {
    func fetchData(_ callback: @escaping (Data) -> Void) {
        // reqeust to server...
        callback(response)
    }
}

When we call fetchData in the code below, we use [weak self] to prevent retain cycles.
I'm using DispatchQueueue.main.async to update the UI in the main thread.
Do I need to have [weak self] here too?
Which one is right, fooA or fooB?

class MyViewController: UIViewController {
    let api = API()
    
    func fooA() {
        api.fetchData { [weak self] data in
            self?.doSomething()
            DispatchQueue.main.async { [weak self] in
                self?.updateUI(data)
            }
        }
    }
    
    func fooB() {
        api.fetchData { [weak self] data in
            self?.doSomething()
            DispatchQueue.main.async {
                self?.updateUI(data)
            }
        }
    }
}
1

There are 1 answers

0
Eric Xue On

weak and unowned propagate:

api.fetchData { [weak self] data in
  // do something with self
  DispatchQueue.main.async { // weak inherited
    // update UI with data
  }
}