Strong vs. Weak Swift 5: What is Weak Self (Xcode 11, 2020)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] [Applause] everyone welcome back to another Swift tutorial today we're going to talk about something that is super important when developing for iOS and it's also a very popular interview question for those of you that are looking to do this professionally and that is what the heck is strong versus weak and weak self as it pertains to memory in iOS so I've got this little diagram here that I found I think it's a really good example of what the heck this stuff is so let me just briefly go through this and then we're gonna dive into some code and see some real world applications so strong versus weak is basically how memory is managed for objects back in the day we used to have to do this manually and now we can just mark things weak or not mark them weak so they're inherently strong and the system manages memory for us so on this diagram on the left here we have these two objects and they both point to each other and both things have a reference count of 1 when both of these things point to each other it actually leaks memory what that means is the system isn't able to clean up a memory or release or deallocate either of these objects because they're cyclically pointing to each other so when one goes away it can't really actually go away what one tries to go away it's like wait a second this one is pointing to me and then consequently when this one tries to go away I'd be de-allocated for a memory it's like wait a second this one's pointing to me so that's where weak comes in so we moved to the right here we see that this arrow is not dashed so the reference count of a guy on the left here is zero and the right is one so what we are basically saying is the parent object is retaining the child in a strong fashion so if the parent goes away the child goes away right and the child is pointing back to the parent in a weak fashion so when the child basically gets created it gets created in a format that's weak so the example that I'll give later on the video is imagine you're walking a dog or the example I'll give later in the video with balloons but imagine you're walking a dog if the person isn't there to hold the leash in an ideal world the dog isn't there right like the dog disappears the dog being walked on a leash is dependent on the person object pointing to it now obviously in the real world the dog would run away but we're not in the real world were in swift land so that said let me stop blabbering on let's take a look at some code examples and hopefully that will paint a good picture for you all to understand quick pause before we get into the video if you haven't seen it already I am hard at work putting together iOS Academy i/o a community where all of us iOS engineers can come together learn how to build some of the top apps like Facebook YouTube and Instagram in addition to interview prep to learn some of these iOS roles at top tech companies so if you're interested in the free and premium content to come head on over to iOS Academy geo and enter your email address into the waitlist form and you will be notified as content becomes available that said let's get into the video all right let's get started by creating a new Xcode project and we're gonna stick with a single View application and I'm gonna call this project my weak versus strong and let's save this on our desktop and let's do two examples that will really hopefully help clarify what weak versus strong is as well as the kind of the point behind it and when you should use one or the other so as I very briefly mentioned in the beginning of this video weak versus strong simply notates how a memory how a objects memories should be retained so a bit of background in a history lesson if you will back in the day you didn't have what we use today that's called automatic reference counting and us iOS developers would have to call things like like if we had an object called food we would have to say food Todd allocate that would allocate some memory for it and whenever we were getting rid of a object or a class or even if controller was disappearing we would have to do something like foo dot release and that would tell the system to release the memory and you can imagine that memory management became difficult because in big apps you have tons of objects sometimes you release an object before it's done being used and it's basically just a whole mess so that Apple came out with this thing called automatic reference counting so automatic reference counting is the notion that if an object is strong it increments account that the system manages that you have this object retained in memory and anything else that's strongly retained increments the number by one and whenever it's de-allocated it decrements it but then there's a difference between strong and weak and the best example that I like to give and for some reason this helps people understand is when you strongly retain something you're basically creating a strong pointer to it and I know I used the word strong in the definition but bear with me so a weak pointer would be something like holding a balloon so if you think of a child that's holding a balloon the child is the strongly retained object and the balloon is the weak object and the relationship there is if the child that's holding the floating balloon goes away so does the balloon basically the weak object is at the mercy of the strong object that is pointing to it and that is truly the entire definition of weak versus strong so you can imagine a problem that you can hit is what if two objects are strongly pointing to each other so the blue needs a person to be there to hold it and the person needs the balloon right and if the person lets go the balloon the blue bullet wouldn't float away that's what we devs would call a retain cycle or a memory leak and I'll mention that that's a very very common interview question so let's actually show an example instead of me kind of going on about this theory so let's say we wanted to show an alert view just a modal pop-up alert on our controller we're gonna do it and viewed it up here if you did appear that's an animated and I'm just using the alert as an example this applies to a lot of cases but if we just create a basic alert which is an alert controller with a title message and style will say title is title message is message and style is alert and we're gonna present this alert animated true and we're also gonna add one action to the alert with the title let's just call it done style will be canceled whoops and this takes a closure with the actual action in and let's say we had a function we want her to call we'll call it do something and in here we would simply call self dot do something now for those of you who kind of have a bit of a background you'll see that this is a problem so this is actually a retain cycle and we would leak memory if we did it this way so let me explain a little bit more so we have this object called view controller this view controller creates this alert which under the hood is just another controller when in alerts action in this case this done button gets triggered in this completion block in the handler closure it references self and basically says called this function which is off of self self in this case refers back to this view controller so you can kind of get a picture of this view controller would be at this point in time referencing and be alert but that one the alert it's actually Nick gets kicked off it then references back to this view controller to get this method so it becomes a loop so the view controller can't be allocated here because obviously it's holding on to the alerts but now that alert even once it goes away off-screen once you hit the button and dismissed it it can't be de-allocated and be released from memory because it's referencing back to yourself to get at this function down here so how do we fix this so it's super simple and if you've done a little bit of Swift you've probably seen this all over the place but we need some reference self in a weak fashion so what we are gonna pass in in brackets here is weak self and now if you actually just call self now this will get a warning and what its gonna tell you is whether you'll get an error and it's gonna tell you basically self is optional so we're gonna do self optional and our code didn't change very much here but this will now guarantee that the actual retained loop gets broken so the viewcontroller would be referencing via alert when the alert pops up when we hit the done button you know optionally because this is weak self we're pointing back to the view controller in a weak fashion which is why we use the keyword weak we would in a weak fashion point back to this function on self which is the view controller so if you ever see weak self in any type of closure when you want to return basically reference back to self that's what it's doing so let's do two more examples that will hopefully help illustrate this I like I said that balloon example that I gave is a in my mind a really good way to think about it anything weak has to be retained by something that's strong if a child holding a balloon goes away and the balloon has helium in it for this example the balloon will float away there's nothing holding on to the balloon so if we do another example and let's say we have a private function of get data let's say get to get some data from like some URL string and it has a completion Handler and this completion handler let's say returns some data this whole block returns void and let's see so then we would let's just pass in the completion nil and let's have another function just called foo and we can say self dot get data and then we can say data in and let's say we had a property on our class and it was called data and it was data optional and let's see once we call this function up here and we come via the completion handler we wanted to assign the results of this property on self you could do this but again that causes a memory leak and this should be capital this causes a memory leak and the reason it causes a memory leak again is you can actually get rid of that from this controller we are referencing this get data right so it comes to this function and it's hypothetically doing some a synchronous task let's say it's getting some like data from like the internet some JSON some API call once you call completion and we come back to this closure and we reference on self assign it to data so we now have a memory leak because we have a retain cycle so what you want to do is add weak self and you can do self question mark because now self is weakly retained and you can assign the data what I meant to do is that originally so if we did in a weak self basically you would do that functionally it's correct but you're leaking memory and you really don't want to leak memory and especially professionally in large projects it is extremely important another thing that you guys will probably see when people reference weak self is people like to do this and I myself like to do this you would basically just unwrap self so because self comes back is optional and you're still using it in a weak fashion because you're retaining it in a weak format but instead of doing self optional you can say strong self dot data this gives you a pointer back to whatever you're retaining weekly which would be this controller and not to confuse all and say that only controllers or self can be retained weekly you could retain anything weekly so by that let me actually give an example of how you can retain something else in a week format so often times you will assign a delegate which is just a protocol so like there's a table of you delegate or something a protocol you might want to assign so let's say we create a protocol and we just call this some delegates and it's going to be any object let's say we have a function in here like did tap thing and let's create another class and let's say we wanted a delegate property off of this view controller also we had a VAR delegate and this is gonna be some delegate optional here we can instantiate our controller like that and let me actually put this in a function or initializer I'll say we see vc delegate is self this would be some delegate and then because it's that some delegate we need to conform and bring in that function like so my point is when we do this this way this is actually also a memory leak and the way that I'm able to understand that it's a memory leak it's not really kind of experience or guessing checking the way that you should acknowledge that this is a memory leak is so this few class creates an instance of view controller so the foo is being basically pointing to view controller in a strong fashion then on view controller you have a property called delegate and you're assigning the delegate to self so now this view controller is pointing back to the foo class in a strong fashion so when foo and view controller are both pointing together it creates a cycle which will that's just set up basically alarms in your head saying this is a memory cycle it's a retain cycle and hence it's a memory leak so how do we fix it it's pretty easy basically you want to say week bar so by marking this week none of this code needs to change however the thing that's different is once this view controller goes away the reference to delegate will be basically dropped and D allocated because it's a week this is very similar to the example of a child holding a balloon once the child goes away in this case foo the balloon which is the delegate that we're pointing to inherently goes away because it's week right it's memory is managed and pointed to by this other strong object so that's really all I really wanted to cover in this video weak self and strong versus weak is extremely and hopefully there's few small examples make it clear what it is don't hesitate to leave comments below if that's not clear if I should do a follow-up video I know myself many many years ago when I first started doing iOS almost 10 years now it took me quite a while to grasp how important this was and also then use it properly because oftentimes what happens is you'll start building stuff and like for example in this case if we didn't have weak self and just it's self dot call this function there's no warning or error or anything here and it functionally works so part of it is well this works perfectly fine why do I quite frankly care so hopefully now you know why you care because if you use too much memory your app is actually gonna crash and it makes your app slow it makes performance bad it makes so many things just are just not great things happen so that said if you haven't smash that like button down below already for the YouTube algorithm make sure you do so subscribe while you're at it if you're new to the channel I love hearing from all of you guys so if there's something down in the comments let me know if this was helpful and if you have any suggestions for future videos thanks for watching and I will see you guys in the next video
Info
Channel: iOS Academy
Views: 23,625
Rating: undefined out of 5
Keywords: swift 5 tutorial, swift strong weak, swift ARC, swift memory, swift for beginners, swift 5 for beginners, swift weak self, swift strong vs. weak, swift retain cycle, swift memory leak, swift delegate memory, swift queue, dispach queue swift, swift, swift 5, swift app, swift ios developer, swift developer, swift course, swift for beginner, learn swift, what is weak self swift, what is strong vs weak in ios, ios strong vs weak, ios weak self, ios retain cycle, ios memory
Id: chI-B8u4MBs
Channel Id: undefined
Length: 16min 40sec (1000 seconds)
Published: Fri Jul 03 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.