0

I have read a tutorial about GCD in swift from https://www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2 In the first part the writer wrote :

DispatchQueue.global(qos: .userInitiated).async { [weak self] in
  guard let self = self else {
    return
  }
  let overlayImage = self.faceOverlayImageFrom(self.image)

  // 2
  DispatchQueue.main.async { [weak self] in
    // 3
    self?.fadeInNewImage(overlayImage)
  }
}

Based on what i know after read swift document from Apple, I think using "unowned" keyword is better because self is a viewcontroller and it has a longer life than closure property. And we also do not need unwrap the optional self. Can you explain more details about this case ? Thanks!

websitesvalues
  • 127
  • 2
  • 2
  • 11
  • 1
    The tutorial is wrong. In this example no capture list is needed. – matt May 01 '19 at 13:26
  • Oh. Thanks! Everything is clear now. – websitesvalues May 01 '19 at 13:32
  • 1
    While it’s not needed, using `[weak self]` is not wrong, and, IMHO, is better than not including it. (E.g. if you dismissed the view controller while `faceOverlayImageFrom` is running, why force it to not release the memory associated with the view controller and its other properties until that method is done?) But using `[unowned self]` would definitely be wrong. Never use it with asynchronous calls. You only use `unowned` when you know that the object in question, `self` in this example, cannot be deallocated before you get to the closure, which is definitely not the case here. – Rob May 01 '19 at 17:02
  • @Rob +1. I had make a test with "unowned keyword" and got a crash. In addition, how can i know that viewcontroller is deallocated or not? I'm new in swift and swift just have only deinit for classes as i know(With objective-c i usually put a log into dealloc func to make sure that all my classes are deallocated) – websitesvalues May 01 '19 at 18:06
  • Well, the view controller is a class, so go ahead and add a `deinit` with a `print` statement (or whatever), just like you used to use `dealloc` in ObjC. The typical way of doing this in an app, tho, is to use `[weak self]` in your closure and if `self` is `nil`, then you know the view controller was deallocated. – Rob May 01 '19 at 22:48

1 Answers1

1

You don't have to worry about strong linking with GCD

DispatchQueue.main.async {
DispatchQueue.global(qos: .userInitiated).async {

so omit any [weal self] / [unowned self]

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87