ARC and Memory Management in Swift | raywenderlich.com

In this tutorial, you’ll learn how ARC works and how to code in Swift for optimal memory management. You’ll learn what reference cycles are, how to use the Xcode 10 visual debugger to discover them when they happen and how to break them using an example of a reference cycle in practice.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/966538-arc-and-memory-management-in-swift

Hi, thanks for this amazing tutorial.

Something I would like you should have added was how static members works with arc.

Sometimes I get confuse which of this one are correct.

UIView.animate(withDuration: 1) {
  self.view.alpha = 0
}

UIView.animate(withDuration: 1) { [weak self] in
  self?.view.alpha = 0
}

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

Hi, @martin06.

Great question! Global functions such as the UIView.animate() family of functions do not require any extra care. Apple states in the Swift guide that they do not capture any values. This means you don’t have to worry about them becoming memory leaks.

Here’s the link for your reference:
https://docs.swift.org/swift-book/LanguageGuide/Closures.html

Hope this clears it up for you.

Hello guys,

Related with Martin’s question for the animate function, isn’t it related with the fact that animation is synchronous executed on the main thread, so the body of the closure cannot, theoretically, outlive the current scope of the function where it is called ?
I am asking this because I am not sure if I am right. I had a quick look into UIKit, and saw that closure is marked with @escaping which means it will get copied on heap, so it might outlive the function body, creating a leak.

Thank you,
Have a nice day!

@ski081 Do you have any feedback about this? Thank you - much appreciated! :]

Hi @2dino1 .

For this simple example, since the block is not attached to self (It’s attached to the animation framework’s static method), then you don’t have a retain cycle. In this case, you don’t have a scenario where self references block which references back to self, so you’re not creating a situation where you’re unable to release an object.

You are right there is no cycle, I got a bit confused.

Much appreciated :slight_smile:
Have a great day !

This tutorial is more than six months old so questions are no longer supported at the moment for it. Thank you!