How to use weak self in Swift | Continued Learning #18

แชร์
ฝัง
  • เผยแพร่เมื่อ 8 ก.พ. 2025
  • Swift uses Automatic Reference Counting (ARC) to manage your app’s memory usage. As a developer, you want to try to keep the ARC count as low as possible, which will keep your app running fast and efficiently. In this video we will learn how to use "weak references" instead of "strong references" to keep our count low!
    This can be quite a confusing topic for new developers, so we will first spend some time reviewing the problem before learning how to implement the solution.
    Learn more about ARC: docs.swift.org...
    Learn more about weak self: www.avanderlee...
    *Note: I am aware that Swift also has "unowned self" which is often mentioned with "weak self". However, if you use "unowned" incorrectly, it will crash you app. Therefore I am only teaching "weak self" in this course as it is safer and more common.
    Next video: • How to use Typealias i...
    Last video: • Multi-threading with b...
    🤙 WELCOME BACK 🤙
    WEBSITE: www.swiftful-t...
    DISCORD: / discord
    GITHUB: github.com/Swi...
    SAY THANKS: www.buymeacoff...

ความคิดเห็น • 94

  • @lowlydeveloper3693
    @lowlydeveloper3693 2 หลายเดือนก่อน +1

    Super important!!! I am so happy that somebody has explained this to me *now* *early* in my Swift learning, before I created huge memory leaks in my production apps!☝👏

  • @ugurdev
    @ugurdev 2 ปีที่แล้ว +5

    Simplest explanation of retain cycles I could find so far. I actually understand why it happens now and what actually happens. Even discovered "Debug Memory Graph" while tinkering which had as many instances of the VM as the count, so at the very least I know how to check for these.
    You have a special gift for teaching Nick! Thanks.

  • @kenjyfukuda
    @kenjyfukuda 3 ปีที่แล้ว +13

    Very pleased to find a final answer/explanation to the intriguing subject of [weak self]. Your explanation is crystal clear and beginner friendly. I'm really enjoying your video series Swiftful Continued Learning. Many thanks.

    • @SwiftfulThinking
      @SwiftfulThinking  3 ปีที่แล้ว

      Glad this helped. It's probably one of the most difficult concepts in iOS development, to be honest!

    • @coffeeCatPeanutDust
      @coffeeCatPeanutDust 3 ปีที่แล้ว

      @@SwiftfulThinking To second Kenj's comment. it being beginner friendly is such a blessing. Thank you as always Nick. Great video.

  • @darinburch9043
    @darinburch9043 3 ปีที่แล้ว +8

    Man you explain things better than most tutorials out there. Thanks!

  • @rdr9999
    @rdr9999 2 หลายเดือนก่อน

    Nick, I’m new to Swift and had struggled with this [weak self] stuff for a while. You really made it crystal clear with this example! Now I understand where I might want to use this, or where I might not want to. You’re really good at explaining these things. Thank you!

  • @wqoq
    @wqoq 3 ปีที่แล้ว +17

    Very simple and clear explanation! Reference counting is something that has always scared me away from Objective-C, and the explanations of ARC I've read in Swift have never really made it any clearer. This is the first time it's ever clicked for me!
    BTW, congrats on reaching 1000 subscribers!

    • @SwiftfulThinking
      @SwiftfulThinking  3 ปีที่แล้ว

      Glad to hear this.. I found this topic pretty complicated when learning as well.... and thanks!!! It's been pretty hard to get subscribers so far (I guess there's a lot of competition in this space), but 1,000 is a big milestone 🥳 Thanks for following along Bob

    • @patilashish
      @patilashish ปีที่แล้ว

      @Nick just a small suggestion. When you are explaining the concept at start of the video, it would be less distracting if the video title fades away. And better yet you show code snippet that you are talking about.

  • @dre5671
    @dre5671 2 ปีที่แล้ว +1

    Very clear, as always! Super grateful for your presence on YT!

  • @morreke
    @morreke 2 ปีที่แล้ว +1

    Your content is golden ! Hope it stays on for a long time so I can come back to review it when needed !

  • @Krafcik226
    @Krafcik226 6 หลายเดือนก่อน

    Best explanation on the internet, THANK YOU!

  • @Mahadev-x7u
    @Mahadev-x7u 3 ปีที่แล้ว +3

    Go Beyond Nick.... Gratitude for all lessons

  • @_marlon
    @_marlon 2 ปีที่แล้ว +1

    Dude, thank you! Your explanation was super clear. Brilliant demo to break this down. This has always been confusing to me as I wasn't sure how the relationship was actually connected. I was confused before because I always wondered how you knew what was gonna be a strong reference. I didn't know it was keeping a class in memory just simply by calling self with a strong reference. Had no idea that simply calling self was THE THING that was creating the strong reference. Hard to explain my confusion with all this, but thank you for making that light go off in my head!🙏

    • @SwiftfulThinking
      @SwiftfulThinking  2 ปีที่แล้ว +2

      Haha yea this is one of the hardest concepts to grasp. Generally, adding weak references will fix a lot of the memory leaks in your app 🥳

  • @tambui3603
    @tambui3603 11 หลายเดือนก่อน

    best video about weak self ever, thank you Nick !

  • @AZMerf
    @AZMerf 3 ปีที่แล้ว +6

    Fantastic stuff. Seems the “strong” self is used in very limited circumstances where you don’t want to lose the action and most of the time use the Weak Self.

    • @SwiftfulThinking
      @SwiftfulThinking  3 ปีที่แล้ว +2

      Yea, that's pretty much it! Adding a weak reference almost always used in asynchronous code and is usually the safer route.

  • @selvarajant
    @selvarajant 2 ปีที่แล้ว +1

    Thats a fantastic explanation with an example. I really appreciate your videos. Thanks a lot.

  • @moisesscn
    @moisesscn ปีที่แล้ว

    Great explanation, Nick. Very clear and concise. Thank you very much for your work

  • @ShowMeLova
    @ShowMeLova 9 หลายเดือนก่อน

    I am so grateful to you Nick! You are so good at explaining. Thanks a lot

  • @harikrishnakeerthipati6767
    @harikrishnakeerthipati6767 2 ปีที่แล้ว +1

    Thank you so much dude. weak self is very clear now.

  • @johnr.5475
    @johnr.5475 3 ปีที่แล้ว +3

    Great video. Useful topic and really well explained. Thanks.

  • @candylover2456
    @candylover2456 2 ปีที่แล้ว

    AMAZING! This was a topic that always confused me, but you made it so simple. Thanks Nick, you're amazing !! :)

    • @SwiftfulThinking
      @SwiftfulThinking  2 ปีที่แล้ว +1

      Haha glad it finally clicked! This is a pretty hard topic!

  • @Reallymellie
    @Reallymellie 2 ปีที่แล้ว +1

    best explanation ever! I am really grateful for your videos!

  • @natgenesis5038
    @natgenesis5038 ปีที่แล้ว

    Very simple and clear explanation

  • @sandarmoe925
    @sandarmoe925 2 ปีที่แล้ว +1

    thanks man... i m so glad i found ur channel

  • @alexanderlichius7069
    @alexanderlichius7069 2 ปีที่แล้ว +1

    Very good explanation, thx for clearing that up!

  • @asankaw1557
    @asankaw1557 ปีที่แล้ว

    Awesome. Finally it makes sense to me. Thanks you.

  • @rkstudio8807
    @rkstudio8807 2 ปีที่แล้ว

    you have taken approx 3 minutes for the solution. but taken 17 minutes to introduce the problem. you have a unique way of teaching. Thank you

  • @ДмитрийСельянов-ы5г
    @ДмитрийСельянов-ы5г 2 หลายเดือนก่อน

    If we talk about the code before 13:00
    Some updates may have been released, but the counter resets when you return to the main page. Init and deinit are also triggered immediately

  • @kavinda_dilshan_paramsoodi
    @kavinda_dilshan_paramsoodi 3 ปีที่แล้ว

    Thank you so much for this video.. This will help me to build my app more efficiently as possible.❤️

  • @akbar_logs
    @akbar_logs ปีที่แล้ว

    Amazingly Explained. 👏🏻

  • @emdutt4012
    @emdutt4012 2 ปีที่แล้ว +1

    Thank u nick for this awesome video..❤

  • @djryanashton
    @djryanashton 2 ปีที่แล้ว +1

    Great explanation. How do you create a strong self on the first time, but weak after that? I imagine that might be useful to get data and save it to the app on the firs try but not subsequently.

  • @tejashsingh2060
    @tejashsingh2060 8 หลายเดือนก่อน

    Amazing explaination !!!!

  • @charlesdurand4381
    @charlesdurand4381 3 ปีที่แล้ว +2

    Great tutorial: thank you !!

  • @dispatchswift
    @dispatchswift 3 ปีที่แล้ว +1

    Another great video. 👏

  • @nirb16
    @nirb16 11 หลายเดือนก่อน

    Great explenation! Thank you for that

  • @DJaySutcliffe
    @DJaySutcliffe ปีที่แล้ว +3

    At around 12:24 mark, when the second view is initialised and the count increases to 1, why when we go back to Screen 1 does Screen 2 not get de-initialised and the count returned to 0?. It only seems to get de-initialised when the Screen 2 is displayed for a second time looking like there will always be a reference held in memory.

    • @helloworld4303
      @helloworld4303 7 หลายเดือนก่อน

      same question here

    • @SwiftfulThinking
      @SwiftfulThinking  หลายเดือนก่อน +1

      I think the NavigationLink may have some built in caching behavior for better UX, but we’ve move away from that for NavigationStack / NavigationDestination now
      (Sorry for the delay I missed this notification)

  • @KulturanCov
    @KulturanCov 2 ปีที่แล้ว +1

    Thank you so much. So what happens when the weak self async task is finally finished? To which vm does it return the data back to? The first, I’m guessing? Weak self basically keeps the first vm alive while normally deinting all following vms and views?

  • @spradohak
    @spradohak ปีที่แล้ว +1

    Hi Nick, great video as always .
    I have a question regarding the init and deinit, following your code example I could see that the view initialize and then deintialize the old one, but If I use navigationStack instead of navigationView, I get a totally different behavior as follows:
    - when you visit the second screen it initialize the view.
    - when you go back to the first screen, it deinitialize the view instantly
    - when you go to the second screen the count goes from 0 to 1 and when you go back the count is 0.
    Could you explain why the behavior is different, because I find this behavior more natural and make sense
    Of course I understand that when you made this video, NavigationStack was not yet introduced since it's part of iOS 16.

  • @Wusagi-gi5xk
    @Wusagi-gi5xk 11 หลายเดือนก่อน

    Ah...This is so much awesome....Thank you...

  • @Nunny25
    @Nunny25 3 ปีที่แล้ว +1

    Thanks Nick, super.

  • @jesperlentz
    @jesperlentz ปีที่แล้ว

    So clear 🙏 thank you!

  • @ayt_daily
    @ayt_daily 3 ปีที่แล้ว +2

    Very clear thankyou so much

  • @emrah309
    @emrah309 2 ปีที่แล้ว +1

    best tutorial!

  • @DerberAlter
    @DerberAlter 2 ปีที่แล้ว

    that was very helpful, thank you!

  • @thomasschatton2920
    @thomasschatton2920 ปีที่แล้ว

    Hey Nick,
    thanks for the great explanation of weak self.
    So with weak self we are enabling the deinit to be called, when the second view is dismissed with the goal to free up resources and guarantee our app staying a fluent expierence.
    With the init we start the execution of getData(), which I put in a background thread. When I call the deinit by dismissing the second view, the app frees up the resource holding the second view, but my background tasks still keeps working.
    Since the result of the background task will not be needed, because second views deinit has been called and therefore the second view does not exist anymore, is there a way to cancel the background task within the deinit to free up even more resources?

  • @fadel_sultan
    @fadel_sultan ปีที่แล้ว

    I took maybe 8 years of study on TH-cam really I don't give anyone more than two or three likes, But for your videos must I give it 1k likes.
    please we need list talking about architecture as MVP and VIPER, I don't know if I write spell that ok or not 😅
    Thank's

  • @_marlon
    @_marlon 2 ปีที่แล้ว +1

    I'm thinking about it now, but I've read that you actually don't need a weak self reference when in animation blocks in UIKit for example

    • @SwiftfulThinking
      @SwiftfulThinking  2 ปีที่แล้ว +2

      Animation blocks usually don’t need weak references. They are almost always done on the main thread and in classes that you don’t deallocate. This is often used for networking and other asynchronous code.

  • @TheSukhreetSingh
    @TheSukhreetSingh 4 หลายเดือนก่อน

    Question: If you used waiting time to be 5 seconds, would that Deinitialize the screen after 5 secs and reduce the count ?

  • @awu878
    @awu878 ปีที่แล้ว

    If I do need this data to download, and I leave this second page, and when the data almost download, I come back to this second screen, does the data download from beginning again?

  • @federicoramos
    @federicoramos 2 ปีที่แล้ว +1

    is it good practise to have only one VM per App? Given it is a simple app, or is it better to have one VM per screen

    • @SwiftfulThinking
      @SwiftfulThinking  2 ปีที่แล้ว +1

      Usually one VM per screen. It is a “View”-Model because it models the data for that View (aka screen)! Sometimes we can share the VM though if multiple screens share the same data.

  • @ec92009y
    @ec92009y 2 ปีที่แล้ว

    I believe failing to release views does not technically slow your app down, at least not directly. What it does is increase the apps memory footprint (that could indirectly cause a slow down). More importantly, that could cause a crash if your app has a chance to create too many of these useless references.

  • @АлексейМоторин-т4о
    @АлексейМоторин-т4о ปีที่แล้ว

    Best!

  • @mygamblingstories5765
    @mygamblingstories5765 3 ปีที่แล้ว +1

    Hi,
    Thank you for your remarkable explanation!
    Only one thing that I can't understand... Why do you always say, "It's okay if this class disappear". In my understanding of OPP - a class is instructions for creating an object, correct? An object should disappear - not a class

    • @SwiftfulThinking
      @SwiftfulThinking  3 ปีที่แล้ว +1

      Oh I see. I'm referring to an instance of the class and not the class itself.

  • @natgenesis5038
    @natgenesis5038 ปีที่แล้ว

    when you will do about Debugging ?

  • @vladimirstepanov7246
    @vladimirstepanov7246 3 ปีที่แล้ว

    Hey ! you are very beautiful to explain)) I will watch your video

  • @TheSpiralnotizblock
    @TheSpiralnotizblock 2 ปีที่แล้ว

    Whats the differents between weak and unwoned?

  • @ZhengCheng
    @ZhengCheng 3 ปีที่แล้ว

    Thank you

  • @william3220
    @william3220 3 ปีที่แล้ว

    Amazing explanation!
    I will use weak! But I have a question!
    when we use "self.data" ,not use weak
    the instance is continuously remain in memory right?
    when I try about 5 times try remain in memory on purpose
    And then when instance remain in the memory , if I load the data until completely download. the data on the UI that is first instance ? or lately instance?
    I'm not sure you can understand my question because I'm not good well English^^
    but I'm wondering about that if use the "self" the first second...until n times.
    which instance is appear in the end in ui.......um..
    I think lately instance appear in the end and another instance is remaining ineffieciently condition in memory..Right?

  • @umairnazim3565
    @umairnazim3565 10 หลายเดือนก่อน +1

    Do we just use weak self with closures?

  • @alextoma402
    @alextoma402 ปีที่แล้ว +1

    Might be because of swiftUI upadates, but for me, every time I go to a new view count goes up one, and when I go back to old view, it get deinitialized and count goes back to 0

    • @SwiftfulThinking
      @SwiftfulThinking  ปีที่แล้ว

      Are you using NavigationStack now?

    • @alextoma402
      @alextoma402 ปีที่แล้ว +1

      @@SwiftfulThinking yea

    • @SwiftfulThinking
      @SwiftfulThinking  ปีที่แล้ว +3

      @@alextoma402I think that’s why. That API is lazy by default.

    • @alextoma402
      @alextoma402 ปีที่แล้ว +1

      @@SwiftfulThinking gotcha. I still got the gist of the lesson either way 🙏🏼

  • @mig12394
    @mig12394 3 ปีที่แล้ว +2

    it is a little difficult to apprehend, if I understand it's mean that we have several time the same class in memory without weak

    • @SwiftfulThinking
      @SwiftfulThinking  3 ปีที่แล้ว

      Hey Michel, yea it sounds like you understand. We basically only want the classes we are using in the memory and we want all "old" classes to deinitialize properly.

  • @mikhailkonovalov3049
    @mikhailkonovalov3049 ปีที่แล้ว

    Somebody knows why print statement dosn't work. I always have an empty console. No worning, no print. nothing? I figured it out. If you have the same issue, it's probably because of the two small buttons in the very right-bottom corner: Show the variables view and Show the consle.

  • @Awesome奥深
    @Awesome奥深 3 ปีที่แล้ว

    Could you please share an video that how to clean mac files to save enough space for xcode installation. I found always waste time to do that, however always could not save enough space.

  • @jerryleeO
    @jerryleeO 6 หลายเดือนก่อน

    Sorry I don't understand why use @observable it doesn't work

  • @RoxieS-pv4ke
    @RoxieS-pv4ke 11 หลายเดือนก่อน

    tell obout unowned self

  • @Rafaglg
    @Rafaglg 7 หลายเดือนก่อน

    hi nick i was wondering if also using
    DispatchQueue.main.async { } needs to be weak self as well? if im refering a variable with self?

    • @SwiftfulThinking
      @SwiftfulThinking  7 หลายเดือนก่อน +1

      We use weak self if there is a chance that “self” gets reallocated before the closure executes. Since DispatchQueue.main.async is happening “almost” immediately, we can assume “self” still exists and therefore do not need it (but it would still work if you have it)