iOS Development

ios – Is that this code nonetheless having a reference cycle?

I’m watching a video on Swift by Sundel, the place he provides some tricks to write extra elegant code.

Initially he had this:

// A view controller that at the moment captures 'self' weakly, in
// order to name a technique on a 'productManager' property object:
class ProductViewController: UIViewController {
    ...

    override func viewDidLoad() {
        tremendous.viewDidLoad()

        buyButton.handler = { [weak self] in
            guard let self = self else {
                return
            }

            self.productManager.startCheckout(for: self.product)
        }
    }
}

He makes use of that [weak self] in and guard let self ... to keep away from retain cycles, which is ok.

Then he creates this utility technique:

// Introducing a 'mix' operate for making use of a price to
// any operate or closure:
func mix<A, B>(
    _ worth: A,
    with closure: @escaping (A) -> B
) -> () -> B {
    return { closure(worth) }
}

After which he replaces the preliminary code with this:

// Utilizing our new mix operate:
class ProductViewController: UIViewController {
    ...

    override func viewDidLoad() {
        tremendous.viewDidLoad()
        
        buyButton.handler = mix(product,
            with: productManager.startCheckout
        )
    }
}

He mentions that as a result of we do not consult with product or productManager utilizing self, there isn’t any extra retain cycle, and the code is cleaner too.

I feel he’s flawed, and his code is similar as:

buyButton.handler = mix(self.product,
    with: self.productManager.startCheckout
)

We use self implicitly, even when we do not write it.

I nonetheless suppose he has a retain cycle.

Please present me a solution whether or not he’s proper or flawed. If he’s certainly proper, I would respect some reason. I simply can’t see it how prevented the retain cycle along with his up to date code.

Thanks prematurely!

Credit: www.ismmailgsm.com

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button