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! :]