Weak and Unowned Self Closure Memory Leak Fixes

Поділитися
Вставка
  • Опубліковано 31 гру 2018
  • It's hard to sometimes demonstrate memory leaks if you're not fully aware of what to look for. In this lesson we'll go over leaks when you introduce the self variable inside of closures. Finally we'll also talk about the fixes.
    Tinder Firestore Swipe and Match
    www.letsbuildthatapp.com/cour...
    Twitter Slide Out Menu Course
    www.letsbuildthatapp.com/cour...
    Podcasts Course
    www.letsbuildthatapp.com/cour...
    Intermediate Training Core Data
    www.letsbuildthatapp.com/cour...
    Instagram Firebase Course
    www.letsbuildthatapp.com/cour...
    Facebook Group
    / 1240636442694543
    Instagram: / buildthatapp
    Twitter: / buildthatapp
    Hackintosh Build
    i9 9900k: amzn.to/2CvQj6v
    ASUS Z390 Motherboard: amzn.to/2JpaQ2B
    16GB Corsair Vengeance RGB RAM: amzn.to/2YbygvJ
    Corsair H100i Platinum Water Cooler: amzn.to/2FnbM22
    Thermaltake RGB Power Supply: amzn.to/2TgKDTu
    Intel 1TB SSD: amzn.to/2Tkdk1V
    Corsair 280x Computer Case: amzn.to/2WcjvH2
    AMD Radeon 4GB RAM GFX Card: amzn.to/2TYMyAp
    LG 34" Widescreen 3440 x 1440: amzn.to/2Tk7q0S
    Rode NT1 Microphone: amzn.to/2TZgX1r
    Focusrite Audio Interface: amzn.to/2U12gey
    Panasonic GH4 DSLR: amzn.to/2U4BrG6
    Magewell HDMI to USB3 Capture Card: amzn.to/2Jp2esI

КОМЕНТАРІ • 95

  • @abdouett3676
    @abdouett3676 5 років тому +3

    A very elegant way to explain a complicated and overlooked concept by many developers in iOS programming. Thanks Brian!

  • @cinquain0
    @cinquain0 5 років тому +2

    Great work Brian. Just bought my first course from you. Thanks again for everything, you've really elevated my iOS skills.

  • @user-ec1dn3uz5k
    @user-ec1dn3uz5k 5 років тому

    Thanks a lot Brian! Enjoying these short snippets that can help make our codebase much cleaner and optimized

  • @zeeshanahmed3716
    @zeeshanahmed3716 5 років тому

    this was really so helpful because its been 1 year I'm working in a company last week I went to another company for the job interview n was asked these three concepts but I didn't knew anyone of them even after having 1 year experience of swift development.... Sometimes we need to keep these small things in mind too. Great stuff you are really going great....

  • @Omeir34
    @Omeir34 5 років тому

    Great video as usual Brian! Pleasure to see you always. Looking forward for the 4th episode of the stretchy header series.

  • @adamm3122
    @adamm3122 5 років тому

    Have been searching for these exact examples all day. Thank you!!! Perfect!!

  • @trunghvbk
    @trunghvbk 5 років тому

    Thank you a lot, it's helpful for me. HAPPY NEW YEAR, Brian!

  • @onurisk5617
    @onurisk5617 5 років тому

    I was facing memory leak for this (Service class) reason and this great video helped me a lot, so thank you so much.

  • @DancesWithDingo
    @DancesWithDingo 5 років тому

    Great stuff Brian, happy new year!

  • @bitj4ke
    @bitj4ke 5 років тому

    Happy new year sir! Greetings from Ph. Thanks for all the tutorials, i learned a lot.

  • @isaacclark9825
    @isaacclark9825 5 років тому

    Nice start to the year!

  • @Dennisvm82
    @Dennisvm82 5 років тому +1

    Thanks for the explanation. I finally understand what they do and when to use them :-)

  • @valentine1925
    @valentine1925 5 років тому

    Happy new year, Brian!!

  • @VasaMusic438
    @VasaMusic438 4 роки тому

    you really teach and explain very good !! Thank you!!

  • @bezeltipis
    @bezeltipis 5 років тому

    Thanks Brian for this knowledge 🤩 👍🏻

  • @sunilaruru9257
    @sunilaruru9257 5 років тому

    Thanks a lot brain for showing very much needed scenarios..

  • @elenekotu
    @elenekotu 5 років тому

    Really nice tutorial, thank you very much

  • @sirajvaliyaveettil232
    @sirajvaliyaveettil232 5 років тому +1

    Hey, Brian. I like the way u explain. Can u make a video on handling Data binding in MVVM.

  • @chimansong8653
    @chimansong8653 3 роки тому

    awesome~!! what a great lesson!

  • @Arun-ow2qb
    @Arun-ow2qb 5 років тому

    You are awesome brain..keep on posting a video about iOS regularly ....you are inspiring us a lot

  • @tachuela2able
    @tachuela2able 5 років тому

    Great video, thanks Brian

  • @Tenly2009
    @Tenly2009 5 років тому +4

    When you call Notification.AddObserver from viewDidLoad like this, do you not end up with multiple observers in memory? One for each time you revisit the redController? Shouldn’t the observer also be removed/deleted when the redController is removed?

  • @nelglezmusic
    @nelglezmusic 5 років тому

    Thanks Brian for the tutorial :)

  • @user-jh6pz7jd7z
    @user-jh6pz7jd7z 5 років тому

    Hello and happy new year! But what if I want to return an array of dictionaries from a completion handler and assign it to a variable of my class Service?

  • @abhisheknaidu1665
    @abhisheknaidu1665 5 років тому

    Thanks a ton Brain.

  • @purplehaton
    @purplehaton 5 років тому

    Thank you for this tutorial. I only cared having closure as variable to use weak self. I understand Notification center holds reference of the view controller. And in the last example, is URLSession’s shared instance holding the reference?

  • @masterload11
    @masterload11 5 років тому

    Thank you so much!

  • @hsksearch3
    @hsksearch3 2 роки тому

    AWESOMEEEEE!!

  • @vamsi3877
    @vamsi3877 5 років тому

    Happy new year brian

  • @ningzedai9052
    @ningzedai9052 2 роки тому +1

    For the last example, in fact there is no retain cycle. The reason that the message of "deinit" is not being printed out is because of @escaping. The "completion" closure is captured by the static "Service" instance. And since it is static, it will always has a reference to the closure, which has a reference to "self". So, you cannot see the "deinit" get called. But there is really no retain cycle.

  • @robertreyes9530
    @robertreyes9530 5 років тому

    Happy New Year Everyone

  • @kohjiarong6452
    @kohjiarong6452 5 років тому

    Hi Brian, what is the implication if I do not manage these memory leaks properly?

  • @Ipadstands
    @Ipadstands 4 роки тому

    Very nice ! Thanks for your putting this out there !! Unowned description could be better though

  • @AbdulBasit-ln6ps
    @AbdulBasit-ln6ps 4 роки тому

    Awsome,

  • @Zainanjum100
    @Zainanjum100 5 років тому

    thanks alot

  • @mozkau_gaming
    @mozkau_gaming 5 років тому

    Good example showing deinit not being triggered. Thanks.

  • @chudq
    @chudq 5 років тому

    Can you do a session on how to use Memory Leak Instrument? I think MLI is a great tool, not only it will detect retain memory leak, but it would also show memory graph so that you have chance to optimize memory management. This tool provides overwhelming information and hard to target memory issues.

  • @kasrababaei4622
    @kasrababaei4622 5 років тому

    Thanks for the video, as AncientUniverseGods mentioned it is very good to see some complicated code. I think that I need to rewatch this video and read more to master this concept. Looking forward to seeing more videos like this. Cheers

  • @dj2mixx429
    @dj2mixx429 5 років тому

    Hi Brian,
    this is not about the Video theme, but I wanted to ask how I can load data from my Firebase Database on an Apple Watch. I didn't find anything about on the Internet. I've built an IOS App using the Firebase Database and I want to create a Watch App for this.
    It would be great if you could help.
    PS: Is there any other Way communicating with you directly?

  • @diyshow888
    @diyshow888 4 роки тому

    Thanks Brain , now I found where my app leak is 👍

  • @jandeveloper
    @jandeveloper 5 років тому

    Hello Brian. Please make a tutorial how to do app with two THEMES, like light and dark. And change it's.

  • @jakubgawecki4264
    @jakubgawecki4264 2 роки тому

    Hey mate, thanks for posting a video. I've been wondering if you could settle some little dispute I have with myself. To my understanding, escaping closures cause memory leaks but only if they are actually going to escape. And that can happen if the closure is assigned to a variable within the class. Following this road, can I assume that this very closure needs to be stored as a variable within the NC instance? If not, how can that happen otherwise? I think what causes a leak here, is not a class holding a reference to another class, but a closure storing a reference to a class. But then again, from what I understand, a closure should not create permanent retain cycles if it will not escape. And how does the one in the Service example escapes? When the execution of it is done, it should be released from memory 🧐Thanks for the help!

  • @sn3aky_pants593
    @sn3aky_pants593 4 роки тому

    In your last example, does the @escaping keyword fix the retain cycle issue for the completion block? Or is the [weak self] still needed?

  • @vandanpatel3395
    @vandanpatel3395 5 років тому +1

    Hi Brian, I have always understood the theory of weak vs unowned, but as a seasoned developer, what are the typical use cases for you to use unowned? We as a team never use unowned at work. Thanks!

    • @VincentBouvier1
      @VincentBouvier1 5 років тому

      I believe unowned in the notification as he did is not safe. Since the observer has not been unregistered, the notification closure can still be called once the notification is posted. Therefore it will unwrap the self variable but it will be nil and will result in a crash.
      As I understand it, use unowned if you are sure that this code will only be called when self is not going to be nil at time of calling. If you are not sure or have a doubt use weak.
      Hope this help and I hope this is all correct. This is how I understood these principles over this tutorial.

  • @georgeshoemaker6872
    @georgeshoemaker6872 4 роки тому

    I have a question: Should weak references always be optionals?

  • @easthastings6919
    @easthastings6919 2 роки тому

    love you dad

  • @lakshmisravyagajavalli9310
    @lakshmisravyagajavalli9310 2 роки тому

    hey why did the showAlert() method not triggered when you added in notificationObserver

    • @LeviM337
      @LeviM337 2 роки тому

      That’s because the the Notification Center closure will only execute when a notification is fired. He’s only observing for a notification and he hasn’t fired a notification from somewhere

  • @mrmr8223
    @mrmr8223 4 роки тому

    Hi thank you for tutorial. I have just only thing that I don't understand is, are we going to use [weak self] only when that closure change the screen?
    Sorry if I have a silly question, I am a beginner. I have read lots of articles about weak and strong reference but I still do not get it clearly about when do I have to call weak variable :(

    • @LetsBuildThatApp
      @LetsBuildThatApp  4 роки тому

      To get an understanding of retain cycles, simply check if deinit is called when you expect it to be. If its not then you have a retain cycle that can be broken with weak self.

  • @yurain3782
    @yurain3782 5 років тому

    I think at the last moment demo you can explain why the alert doesn't show up(self?.showAlert()). If it changes from weak to unowned, it will crash.

  • @smackaroony
    @smackaroony 5 років тому

    New year new you

  • @moosegoose1282
    @moosegoose1282 5 років тому

    so to be safe, it's recommend to always make sure to not have strong reference? for example in the firebase course when fetching user data, should we also use weak/unowned? thanks dad

    • @LetsBuildThatApp
      @LetsBuildThatApp  5 років тому

      Yep, I would recommend verifying first if the firebase completion blocks cause any type of retain cycles. There are many instances where the [weak self] stuff isn't needed.

  • @Jaimeicz
    @Jaimeicz 5 років тому

    So.. everytime we use a closure we should declare weak self? because if we go back the view controller will still be on memory right?

    • @zz9364
      @zz9364 5 років тому

      I declare weak self in closure everytime.

  • @aafaqahmed2265
    @aafaqahmed2265 3 роки тому

    Premium stuff!

  • @osmanmusse6223
    @osmanmusse6223 5 років тому

    cool video brain

  • @P_F_D
    @P_F_D 5 років тому

    thanks for the video
    I find weak self far safer than unowned self, as you can easily end up crashing your app if you're not careful with unowned. For instance, if you use unowned in an animation block, then you exit the controller during an animation, you will crash (as self becomes nil)

    • @LetsBuildThatApp
      @LetsBuildThatApp  5 років тому +1

      Indeed unowned is very dangerous if one does not know its proper usages. You'll get owned by the crashes....

  • @TrejoMundos
    @TrejoMundos 5 років тому

    Thank you! :D I will fix all the retain cycles of the current App of my company that I´m working. It has a lot of it! on every ViewController haha :/! A lot work of to do.

  • @prachibile2798
    @prachibile2798 3 роки тому

    Hello friend, I really like your all videos but I am curious to know why do you do UI programmatically and not using storyboard?

    • @LetsBuildThatApp
      @LetsBuildThatApp  3 роки тому

      Storyboard is like a microwave, whereas code is having an actual kitchen.

    • @prachibile2798
      @prachibile2798 3 роки тому

      @@LetsBuildThatApp Ohh... waww... nicely explained :) I liked your way of doing code.

  • @Ahmed-Salah87
    @Ahmed-Salah87 5 років тому

    Big Like for you :D

  • @gevorgnikoghosyan7252
    @gevorgnikoghosyan7252 3 роки тому

    please can you make an video about weak and unowned so we could understand deep ? i had an interview and i couldn't explain it :( i tryed to say yes unowned if i guarantee there wouldnt be nill weak can be nil but unfortunatly they stoped me at that point "" can you explain why????"" and i had no clue why(

  • @MoAdel92
    @MoAdel92 3 роки тому

    where is the alert?

  • @shazShanee693
    @shazShanee693 5 років тому

    Why is it so difficult to expain owned and self
    Any easy way to tell us?

  • @nathanchen107
    @nathanchen107 5 років тому

    Hi Brian, the examples are not retain cycle examples, they’re only one Singleton object holding a strong reference to the red viewcontroller, if they were not Singleton, memory leaks wont happen

    • @LetsBuildThatApp
      @LetsBuildThatApp  5 років тому

      Hey Yang, as long as two objects have references to each other, that's known to be a retain cycle and should be avoided. This is at least my understanding of what retain cycles are. In the previous video, I showed another retain cycle with a non singleton object that can be broken using a weak var reference. Hope that helps.

    • @nathanchen107
      @nathanchen107 5 років тому

      Lets Build That App Hi Brian, thanks for replying back, but in the example the viewcontoller is not holding a strong reference to the singletons created, only the Singleton is referencing the viewcontroller, let me know if I’m wrong, thanks

    •  5 років тому

      @@nathanchen107 Singletons or lets say static variables are kept in a memory and they are not deallocated during the run of the application. Or do you expect that your shared property is deallocated if you are not using it? So by design it is kept in memory, also holding a reference of the ViewController -> retain cycle.
      Also for Brian. I appreciate your effort that you put into your videos and I also like the content, but sometimes it would be really good to explain how these things work under the hood. Usually it is not so hard to explain and people would understand it better then blindly using [weak self] everywhere. It applies to any topic.

    • @LetsBuildThatApp
      @LetsBuildThatApp  5 років тому +1

      Both of you are correct, I think I was confusing the Singleton with a variable closure instance. The terminology is something I have yet to get used to using.

  • @mcnimi
    @mcnimi 5 років тому

    at the beginning of every closure you can declare:
    guard let self = `self` else { return }
    and the self will not be optional

    • @LetsBuildThatApp
      @LetsBuildThatApp  5 років тому

      You could, but this is what we refer to as a hack. Although, the weak self stuff isn't any better.

    • @manuelmartin6132
      @manuelmartin6132 5 років тому +1

      @@LetsBuildThatApp Since Swift 4.2 it is possible to use this:
      networkRequest.fetchData() { [weak self] result in
      guard let self = self else { return } // Implemented (Swift 4.2)
      switch result {
      case .succeeded(let data):
      self.processData(data)
      case .failed(let error):
      self.handleError(error)
      }
      }
      github.com/apple/swift-evolution/blob/master/proposals/0079-upgrade-self-from-weak-to-strong.md

    • @LetsBuildThatApp
      @LetsBuildThatApp  5 років тому

      Alas a lot of syntax dancing we have to perform :(

  • @PitiphongPhongpattranont
    @PitiphongPhongpattranont 5 років тому

    I think you understand the retain cycle wrong in the case of Notification Center and Data Task
    The Notification Center is the one who own the closure not the RedViewController and the URLSessionDataTask is the one who own for the Session case which means that those two cases are not Retain Cycle

    • @LetsBuildThatApp
      @LetsBuildThatApp  5 років тому

      Yes I believe I mixed up the terminology with strong references vs retain cycles. It's all very confusing to explain correctly.

    • @PitiphongPhongpattranont
      @PitiphongPhongpattranont 5 років тому

      Yeah, my point and concern is that you didn’t provide a correct solution for the Notification Center and your audience may do it incorrectly in their real work

  • @Gojam12
    @Gojam12 4 роки тому

    Lets see, was this a very simple example? Oh ok thought I heard that like 12 times lol

  • @silver10188
    @silver10188 5 років тому

    So anytime we call a closure from another class, we need a weak self?

    • @LetsBuildThatApp
      @LetsBuildThatApp  5 років тому

      Only if you determine that it creates a retain cycle. Not all closures do.

  • @ChristopherCricketWallace
    @ChristopherCricketWallace 3 роки тому

    good example case. confusing explanation.

  • @Gojam12
    @Gojam12 4 роки тому

    What an oddball, I'll stick with Paul Hagerty, there is a much better way to do this.

  • @finalpets
    @finalpets 5 років тому

    666 Likes !!!! Remove [weak self] to the like button

  • @auronedgevicks7739
    @auronedgevicks7739 2 роки тому

    I think a more simpler example would have worked

  • @user-up8fj4cp1y
    @user-up8fj4cp1y 7 місяців тому

    Your example(s) are flawed. It is the alert presentation that is causing the memory leak because it can't be dismissed. If you replace the code inside showAlert() with a print(), the memory is reclaimed just fine. (I used your code verbatim, with that one change.) The reason is simple: you never manually provide an OK dismiss button for the alert so it never goes away / deallocates.

    • @bortanradu
      @bortanradu 3 місяці тому

      His example isn't wrong. In your case you don't get a retain cycle when you replace self.showAlert() with print() because you remove the line of code that references self. The retain cycle only happens if inside of the closure you need to use self.

  • @souravdeb6126
    @souravdeb6126 3 роки тому

    You just showed HOW retain cycles are obtained, NOT WHY. Big down-point.