Confusion about where to put [unoccupied self]

I have a closed loop, so my viewcontroller deinit will not be called, and I'm trying to resolve this to my [unowned self] addition, but I'm not too sure where to put unowned in my cases:

Case 1

class YADetailiViewController: UIViewController {
 var subscription: Subscription<YAEvent>?

 override func viewDidLoad() {
    super.viewDidLoad()
    if let query = self.event.subscribeQuery() {
        self.subscription = Client.shared.subscribe(query)
        self.subscription?.handle(Event.updated) {
            query, object in
            DispatchQueue.main.async {
                [unowned self] in// Put unowned here won't break the cycle, but it does compile and run 
                self.pageViewLabel.text = String(object.pageViews) + " VIEW" + ((object.pageViews > 1) ? "S" : "")
            }
        }
    }
 }
}

Case 2

 override func viewDidLoad() {
    super.viewDidLoad()
    if let query = self.event.subscribeQuery() {
        self.subscription = Client.shared.subscribe(query)
        self.subscription?.handle(Event.updated) {
            [unowned self] query, object in // Put unowned breaks the cycle, and deinit is called
                DispatchQueue.main.async { 
                    self.pageViewLabel.text = String(object.pageViews) + " VIEW" + ((object.pageViews > 1) ? "S" : "")
                }
            }
        }
    }

I am curious what the differences are between the two scenarios and why they work, but not the others.

+4
source share
1 answer

In fact, as @matt correctly says, the problem is with capture time self. Actually int this code is selfcaptured twice:

  • When an external closure is passed to a method handle
  • When the inner closure is passed to the method async(during the execution of the closure handle)

self , .

: self (YADetailiViewController) → subscription → (handle) → self. , self () . .

self ( ) , , async - .

. self , ( ) .

handle , /, , @AdrianBobrowski, weak unowned, .

+1

Source: https://habr.com/ru/post/1693494/


All Articles