iOS Design Patterns - Part 3: MVC-N | Ray Wenderlich

:+1: I could see this working well.

I personally tend to use GCD and URLSessionTask a lot, which has a lot of overlap with operations.

The main weakness, as you hint at, is grouping tasks together. I can see operations being a great way to do this.

Iā€™m lazy ;] and havenā€™t been forced to implement cancellation logic for chained networking tasks recently, so Iā€™ve just been ignoring this. However, I will take another look at operations to do just this.

Thanks for the recommendation. :]

Why you didnā€™t write loadProducts like this ?

internal func loadProducts() {
    collectionView.refreshControl?.beginRefreshing()
    networkClient.getProducts(forType: .business, success: { products in
      self.products = products
      self.collectionView.reloadData()
      self.collectionView.refreshControl?.endRefreshing()
      
      }, failure: { [weak self] error in
        guard let strongSelf = self else { return }
        strongSelf.collectionView.refreshControl?.endRefreshing()
        print("Product download failed: \(error)")
    })
  }

What is the purpose of [week self] and then define strong one?

It breaks a possible strong reference cycle that can happen if network client outlives the view controller

You mean sometimes controller die before receiving data from server? and this may cause app crash?Am I right?

The concern isnā€™t that the app will crash, but rather, that the view controller will be around for longer than it should beā€¦ basically, the closure would capture the view controller if self was used without making it weak, which could extend its lifetime.

See this excellent article on References in Swift for a full explanation.

This sentence basically sums it up:

ā€œIf any variable is declared outside of the closureā€™s scope, referencing that variable inside the closureā€™s scope creates another strong reference to that object.ā€

In general, itā€™s a good idea to specify [weak self] when using self passed into an @escaping closure, which is exactly whatā€™s happening here. Creating strongSelf creates a temporary strong reference to self, if itā€™s not nil, when the closure is executingā€¦ basically, itā€™s so you donā€™t have to write self? everywhere within the closure.

1 Like

@jrg.developer - Going through some feature videos and old examples and found rwcleanbackend.herokuapp.com is down again. Can you please check?

Iā€™ve restarted it manually.

It can usually recover by itself, but it does sleep after a period of inactivityā€¦ itā€™s just on a free Heroku instance.

Cheers! :]

Looks like rwcleanbackend.herokuapp.com is down again.

@jrg.developer Can you please help with this when you get a chance? Thank you - much appreciated! :]