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

Поділитися
Вставка
  • Опубліковано 8 вер 2024
  • 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...

КОМЕНТАРІ • 89

  • @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 роки тому +7

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

  • @maguirer
    @maguirer 3 роки тому +18

    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.

  • @ugurdev
    @ugurdev Рік тому +4

    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.

  • @Krafcik226
    @Krafcik226 Місяць тому

    Best explanation on the internet, THANK YOU!

  • @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.

  • @andrejkling3886
    @andrejkling3886 3 роки тому +3

    Go Beyond Nick.... Gratitude for all lessons

  • @ShowMeLova
    @ShowMeLova 4 місяці тому

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

  • @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 !

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

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

  • @johnr.5475
    @johnr.5475 3 роки тому +3

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

  • @_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 🥳

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

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

  • @tambui3603
    @tambui3603 6 місяців тому

    best video about weak self ever, thank you Nick !

  • @sandarmoe925
    @sandarmoe925 Рік тому +1

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

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

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

  • @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.

  • @asankaw1557
    @asankaw1557 Рік тому

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

  • @moisesscn
    @moisesscn Рік тому

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

  • @emdutt4012
    @emdutt4012 Рік тому +1

    Thank u nick for this awesome video..❤

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

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

  • @akbar_logs
    @akbar_logs 9 місяців тому

    Amazingly Explained. 👏🏻

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

    Amazing explaination !!!!

  • @ayt_daily
    @ayt_daily 3 роки тому +2

    Very clear thankyou so much

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

    Very good explanation, thx for clearing that up!

  • @Nunny25
    @Nunny25 3 роки тому +1

    Thanks Nick, super.

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

    best tutorial!

  • @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!

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

    swift king !

  • @nirb16
    @nirb16 6 місяців тому

    Great explenation! Thank you for that

  • @Wusagi-gi5xk
    @Wusagi-gi5xk 6 місяців тому

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

  • @natgenesis5038
    @natgenesis5038 Рік тому

    Very simple and clear explanation

  • @rkstudio8807
    @rkstudio8807 Рік тому

    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

  • @charlesdurand4381
    @charlesdurand4381 3 роки тому +2

    Great tutorial: thank you !!

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

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

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

    Another great video. 👏

  • @jesperlentz
    @jesperlentz Рік тому

    So clear 🙏 thank you!

  • @djryanashton
    @djryanashton Рік тому +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.

  • @DerberAlter
    @DerberAlter Рік тому

    that was very helpful, thank you!

  • @fadel_sultan
    @fadel_sultan Рік тому

    I took maybe 8 years of study on UA-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

  • @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?

  • @_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.

  • @user-cj3fs9bx9z
    @user-cj3fs9bx9z 9 місяців тому

    Best!

  • @DJaySutcliffe
    @DJaySutcliffe 10 місяців тому +1

    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.

  • @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.

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

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

  • @ec92009y
    @ec92009y Рік тому

    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.

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

    Thank you

  • @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.

  • @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?

  • @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.

  • @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?

  • @alextoma402
    @alextoma402 10 місяців тому +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  10 місяців тому

      Are you using NavigationStack now?

    • @alextoma402
      @alextoma402 10 місяців тому +1

      @@SwiftfulThinking yea

    • @SwiftfulThinking
      @SwiftfulThinking  10 місяців тому +3

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

    • @alextoma402
      @alextoma402 10 місяців тому +1

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

  • @jerryleeO
    @jerryleeO Місяць тому

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

  • @natgenesis5038
    @natgenesis5038 Рік тому

    when you will do about Debugging ?

  • @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.

  • @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 5 місяців тому +1

    Do we just use weak self with closures?

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

    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.

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

    Whats the differents between weak and unwoned?

  • @RoxieS-pv4ke
    @RoxieS-pv4ke 6 місяців тому

    tell obout unowned self

  • @loggioRafa
    @loggioRafa 2 місяці тому

    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  2 місяці тому +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)