Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Weak, Strong, Unowned, Oh My!

Weak, Strong, Unowned, Oh My!

Let’s dig into something we’re all afraid to look at talk about. ARC is that family member that we all hate to love. Unfortunately, he needs our help quite often (more often than we’d like!). I want to discuss retain cycles. Swift is much better at helping us help ARC know how to manage our memory by giving us cool little things like capture lists, unowned, and weak references. We’ll generate some retain cycles of our own, explore how to debug them with Instruments, and learn how to use the tools Swift gives us to have clear, expressive, non-leaky code.

Hector Matos

August 04, 2015
Tweet

More Decks by Hector Matos

Other Decks in Programming

Transcript

  1. ARC

  2. - (void)releaseTheKraken { Kraken *kraken = [[Kraken alloc] init]; //+1

    retain [kraken release]; //generated by ARC }
  3. Now Stop, Example Time //Kraken holds a strong reference to

    the yummy human. class Kraken { var yummyHuman: Human }
  4. // The animation closure holds a strong reference to self

    // self.retainCount is 1 here UIView.animateWithDuration(0.3) { // self.retainCount is 2 here self.view.alpha = 0.0 }
  5. Stop, Collaborate, & Listen! (to my next example) class KrakensFace:

    UIView { @IBOutlet weak var razorSharpTeeth: UIView! } KrakenAPI.eat(yummyHuman, whenFinished: { [weak self] in self?.waitForNextMealTime() })
  6. Capture Lists It's just an array. That's all it is.

    There, there. It's all over now. !
  7. class Human { var heart: ! func seeKrakenComing() { heart.haveHeartAttack()

    } } class !: Organ { unowned let human: Human init(human: Human) { self.human = human } func haveHeartAttack() { human.die() } } let human = Human() human.heart = !(human: human)