Weak and Unowned Self Closure Memory Leak Fixes

  Рет қаралды 56,999

Lets Build That App

Lets Build That App

Күн бұрын

Пікірлер
@abdouett3676
@abdouett3676 6 жыл бұрын
A very elegant way to explain a complicated and overlooked concept by many developers in iOS programming. Thanks Brian!
@zeeshanahmed3716
@zeeshanahmed3716 6 жыл бұрын
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....
@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.
@user-ec1dn3uz5k
@user-ec1dn3uz5k 6 жыл бұрын
Thanks a lot Brian! Enjoying these short snippets that can help make our codebase much cleaner and optimized
@cinquain0
@cinquain0 6 жыл бұрын
Great work Brian. Just bought my first course from you. Thanks again for everything, you've really elevated my iOS skills.
@isaacclark9825
@isaacclark9825 6 жыл бұрын
Nice start to the year!
@adamm3122
@adamm3122 5 жыл бұрын
Have been searching for these exact examples all day. Thank you!!! Perfect!!
@Tenly2009
@Tenly2009 5 жыл бұрын
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?
@ningzedai9052
@ningzedai9052 3 жыл бұрын
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.
@Omeir34
@Omeir34 6 жыл бұрын
Great video as usual Brian! Pleasure to see you always. Looking forward for the 4th episode of the stretchy header series.
@DancesWithDingo
@DancesWithDingo 6 жыл бұрын
Great stuff Brian, happy new year!
@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.
@chimansong8653
@chimansong8653 4 жыл бұрын
awesome~!! what a great lesson!
@sirajvaliyaveettil232
@sirajvaliyaveettil232 6 жыл бұрын
Hey, Brian. I like the way u explain. Can u make a video on handling Data binding in MVVM.
@nelglezmusic
@nelglezmusic 6 жыл бұрын
Thanks Brian for the tutorial :)
@valentine1925
@valentine1925 6 жыл бұрын
Happy new year, Brian!!
@trunghvbk
@trunghvbk 6 жыл бұрын
Thank you a lot, it's helpful for me. HAPPY NEW YEAR, Brian!
@VasaMusic438
@VasaMusic438 4 жыл бұрын
you really teach and explain very good !! Thank you!!
@twentyonetwentysix
@twentyonetwentysix 3 ай бұрын
It is very intersting how manually you have to release resources with weak or unowoned. In the world of Android we had used weak references in the past, but now as we are working with the components lifecycyle our asynchronous work is chained to it and also publishing events. So in the case a red screen like in this example is gone, those closures are never going to be invoked, as everything is tied to the lifecyycle of the screen.
@bitj4ke
@bitj4ke 6 жыл бұрын
Happy new year sir! Greetings from Ph. Thanks for all the tutorials, i learned a lot.
@mozkau_gaming
@mozkau_gaming 5 жыл бұрын
Good example showing deinit not being triggered. Thanks.
@sunilaruru9257
@sunilaruru9257 5 жыл бұрын
Thanks a lot brain for showing very much needed scenarios..
@vandanpatel3395
@vandanpatel3395 6 жыл бұрын
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.
@tachuela2able
@tachuela2able 6 жыл бұрын
Great video, thanks Brian
@Arun-ow2qb
@Arun-ow2qb 6 жыл бұрын
You are awesome brain..keep on posting a video about iOS regularly ....you are inspiring us a lot
@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.
@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!
@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.
@diyshow888
@diyshow888 4 жыл бұрын
Thanks Brain , now I found where my app leak is 👍
@kohjiarong6452
@kohjiarong6452 5 жыл бұрын
Hi Brian, what is the implication if I do not manage these memory leaks properly?
@Dennisvm82
@Dennisvm82 6 жыл бұрын
Thanks for the explanation. I finally understand what they do and when to use them :-)
@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?
@ΓιώργοςΣαράντος-ρ6ζ
@ΓιώργοςΣαράντος-ρ6ζ 6 жыл бұрын
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?
@hsksearch3
@hsksearch3 2 жыл бұрын
AWESOMEEEEE!!
@Ipadstands
@Ipadstands 4 жыл бұрын
Very nice ! Thanks for your putting this out there !! Unowned description could be better though
@sn3aky_pants593
@sn3aky_pants593 5 жыл бұрын
In your last example, does the @escaping keyword fix the retain cycle issue for the completion block? Or is the [weak self] still needed?
@LetsBuildThatApp
@LetsBuildThatApp 5 жыл бұрын
Escaping is something very different.
@elenekotu
@elenekotu 6 жыл бұрын
Really nice tutorial, thank you very much
@bezeltipis
@bezeltipis 6 жыл бұрын
Thanks Brian for this knowledge 🤩 👍🏻
@dj2mixx429
@dj2mixx429 6 жыл бұрын
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?
@P_F_D
@P_F_D 6 жыл бұрын
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 6 жыл бұрын
Indeed unowned is very dangerous if one does not know its proper usages. You'll get owned by the crashes....
@moosegoose1282
@moosegoose1282 6 жыл бұрын
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 6 жыл бұрын
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.
@vamsi3877
@vamsi3877 6 жыл бұрын
Happy new year brian
@jandeveloper
@jandeveloper 6 жыл бұрын
Hello Brian. Please make a tutorial how to do app with two THEMES, like light and dark. And change it's.
@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.
@lakshmisravyagajavalli9310
@lakshmisravyagajavalli9310 3 жыл бұрын
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
@abhisheknaidu1665
@abhisheknaidu1665 5 жыл бұрын
Thanks a ton Brain.
@masterload11
@masterload11 6 жыл бұрын
Thank you so much!
@robertreyes9530
@robertreyes9530 6 жыл бұрын
Happy New Year Everyone
@gevorgnikoghosyan7252
@gevorgnikoghosyan7252 4 жыл бұрын
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(
@georgeshoemaker6872
@georgeshoemaker6872 4 жыл бұрын
I have a question: Should weak references always be optionals?
@afaaqahmedsaqi
@afaaqahmedsaqi 3 жыл бұрын
Premium stuff!
@AbdulBasit-ln6ps
@AbdulBasit-ln6ps 4 жыл бұрын
Awsome,
@easthastings6919
@easthastings6919 2 жыл бұрын
love you dad
@Jaimeicz
@Jaimeicz 6 жыл бұрын
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 6 жыл бұрын
I declare weak self in closure everytime.
@nathanchen107
@nathanchen107 6 жыл бұрын
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 6 жыл бұрын
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 6 жыл бұрын
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
6 жыл бұрын
@@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 6 жыл бұрын
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.
@PitiphongPhongpattranont
@PitiphongPhongpattranont 6 жыл бұрын
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 6 жыл бұрын
Yes I believe I mixed up the terminology with strong references vs retain cycles. It's all very confusing to explain correctly.
@PitiphongPhongpattranont
@PitiphongPhongpattranont 6 жыл бұрын
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
@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
@mcnimi
@mcnimi 6 жыл бұрын
at the beginning of every closure you can declare: guard let self = `self` else { return } and the self will not be optional
@LetsBuildThatApp
@LetsBuildThatApp 6 жыл бұрын
You could, but this is what we refer to as a hack. Although, the weak self stuff isn't any better.
@manuelmartin6132
@manuelmartin6132 6 жыл бұрын
@@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 6 жыл бұрын
Alas a lot of syntax dancing we have to perform :(
@Zainanjum100
@Zainanjum100 6 жыл бұрын
thanks alot
@smackaroony
@smackaroony 6 жыл бұрын
New year new you
@osmanmusse6223
@osmanmusse6223 6 жыл бұрын
cool video brain
@Ahmed-Salah87
@Ahmed-Salah87 6 жыл бұрын
Big Like for you :D
@MoAdel92
@MoAdel92 3 жыл бұрын
where is the alert?
@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.
@shazShanee693
@shazShanee693 5 жыл бұрын
Why is it so difficult to expain owned and self Any easy way to tell us?
@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.
@Gojam12
@Gojam12 4 жыл бұрын
What an oddball, I'll stick with Paul Hagerty, there is a much better way to do this.
@Gojam12
@Gojam12 4 жыл бұрын
Lets see, was this a very simple example? Oh ok thought I heard that like 12 times lol
@LetsBuildThatApp
@LetsBuildThatApp 4 жыл бұрын
I am the god of simple examples.
@ChristopherCricketWallace
@ChristopherCricketWallace 3 жыл бұрын
good example case. confusing explanation.
@auronedgevicks7739
@auronedgevicks7739 3 жыл бұрын
I think a more simpler example would have worked
@art-o9r
@art-o9r 11 ай бұрын
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 7 ай бұрын
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.
@finalpets
@finalpets 5 жыл бұрын
666 Likes !!!! Remove [weak self] to the like button
Swift Closures Explained
14:23
Sean Allen
Рет қаралды 68 М.
Retain Cycles: How to Detect with Instruments Profiler!
13:55
Lets Build That App
Рет қаралды 49 М.
Deadpool family by Tsuriki Show
00:12
Tsuriki Show
Рет қаралды 4,8 МЛН
Quando A Diferença De Altura É Muito Grande 😲😂
00:12
Mari Maria
Рет қаралды 19 МЛН
Top 10 Trending AI Tools This Week: Revolutionize Your Work & Life
15:06
ManuAGI - AutoGPT Tutorials
Рет қаралды 105
Difference between weak and unowned in Swift
16:20
Code Cat
Рет қаралды 15 М.
When to Semaphore vs Dispatch Group! Careful Multithreaded Shared Resource
11:11
JavaScript Memory Leaks and How To Fix Them
14:58
Software Developer Diaries
Рет қаралды 30 М.
Solving A Classic Google Interview Logic Puzzle
9:03
MindYourDecisions
Рет қаралды 8 МЛН
Memory Leaks in iOS: Find, Diagnose, & Fix (2022)
12:44
iOS Academy
Рет қаралды 52 М.
How to use weak self in Swift | Continued Learning #18
20:33
Swiftful Thinking
Рет қаралды 18 М.
Swift - Stack vs Heap
9:58
Swift Arcade
Рет қаралды 7 М.
A Color Test That Can Tell Your Mental Age
7:37
BRIGHT SIDE
Рет қаралды 45 МЛН