Weak and Unowned Self Closure Memory Leak Fixes

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

Lets Build That App

Lets Build That App

5 жыл бұрын

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 жыл бұрын
A very elegant way to explain a complicated and overlooked concept by many developers in iOS programming. Thanks Brian!
@user-ec1dn3uz5k
@user-ec1dn3uz5k 5 жыл бұрын
Thanks a lot Brian! Enjoying these short snippets that can help make our codebase much cleaner and optimized
@cinquain0
@cinquain0 5 жыл бұрын
Great work Brian. Just bought my first course from you. Thanks again for everything, you've really elevated my iOS skills.
@adamm3122
@adamm3122 5 жыл бұрын
Have been searching for these exact examples all day. Thank you!!! Perfect!!
@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....
@trunghvbk
@trunghvbk 5 жыл бұрын
Thank you a lot, it's helpful for me. HAPPY NEW YEAR, Brian!
@Omeir34
@Omeir34 5 жыл бұрын
Great video as usual Brian! Pleasure to see you always. Looking forward for the 4th episode of the stretchy header series.
@isaacclark9825
@isaacclark9825 5 жыл бұрын
Nice start to the year!
@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!
@VasaMusic438
@VasaMusic438 4 жыл бұрын
you really teach and explain very good !! Thank you!!
@valentine1925
@valentine1925 5 жыл бұрын
Happy new year, Brian!!
@chimansong8653
@chimansong8653 3 жыл бұрын
awesome~!! what a great lesson!
@bitj4ke
@bitj4ke 5 жыл бұрын
Happy new year sir! Greetings from Ph. Thanks for all the tutorials, i learned a lot.
@sunilaruru9257
@sunilaruru9257 5 жыл бұрын
Thanks a lot brain for showing very much needed scenarios..
@bezeltipis
@bezeltipis 5 жыл бұрын
Thanks Brian for this knowledge 🤩 👍🏻
@Dennisvm82
@Dennisvm82 5 жыл бұрын
Thanks for the explanation. I finally understand what they do and when to use them :-)
@tachuela2able
@tachuela2able 5 жыл бұрын
Great video, thanks Brian
@elenekotu
@elenekotu 5 жыл бұрын
Really nice tutorial, thank you very much
@Arun-ow2qb
@Arun-ow2qb 5 жыл бұрын
You are awesome brain..keep on posting a video about iOS regularly ....you are inspiring us a lot
@nelglezmusic
@nelglezmusic 5 жыл бұрын
Thanks Brian for the tutorial :)
@abhisheknaidu1665
@abhisheknaidu1665 5 жыл бұрын
Thanks a ton Brain.
@masterload11
@masterload11 5 жыл бұрын
Thank you so much!
@vamsi3877
@vamsi3877 5 жыл бұрын
Happy new year brian
@sirajvaliyaveettil232
@sirajvaliyaveettil232 5 жыл бұрын
Hey, Brian. I like the way u explain. Can u make a video on handling Data binding in MVVM.
@hsksearch3
@hsksearch3 2 жыл бұрын
AWESOMEEEEE!!
@mozkau_gaming
@mozkau_gaming 5 жыл бұрын
Good example showing deinit not being triggered. Thanks.
@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
@diyshow888
@diyshow888 4 жыл бұрын
Thanks Brain , now I found where my app leak is 👍
@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?
@robertreyes9530
@robertreyes9530 5 жыл бұрын
Happy New Year Everyone
@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.
@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?
@easthastings6919
@easthastings6919 2 жыл бұрын
love you dad
@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
@aafaqahmed2265
@aafaqahmed2265 3 жыл бұрын
Premium stuff!
@ningzedai9052
@ningzedai9052 2 жыл бұрын
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.
@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?
@jandeveloper
@jandeveloper 5 жыл бұрын
Hello Brian. Please make a tutorial how to do app with two THEMES, like light and dark. And change it's.
@kohjiarong6452
@kohjiarong6452 5 жыл бұрын
Hi Brian, what is the implication if I do not manage these memory leaks properly?
@smackaroony
@smackaroony 5 жыл бұрын
New year new you
@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.
@osmanmusse6223
@osmanmusse6223 5 жыл бұрын
cool video brain
@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!
@vandanpatel3395
@vandanpatel3395 5 жыл бұрын
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.
@Ahmed-Salah87
@Ahmed-Salah87 5 жыл бұрын
Big Like for you :D
@georgeshoemaker6872
@georgeshoemaker6872 4 жыл бұрын
I have a question: Should weak references always be optionals?
@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?
@LetsBuildThatApp
@LetsBuildThatApp 4 жыл бұрын
Escaping is something very different.
@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.
@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.
@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 жыл бұрын
Indeed unowned is very dangerous if one does not know its proper usages. You'll get owned by the crashes....
@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?
@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.
@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.
@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.
@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?
@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 жыл бұрын
@@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
@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 жыл бұрын
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.
@shazShanee693
@shazShanee693 5 жыл бұрын
Why is it so difficult to expain owned and self Any easy way to tell us?
@ChristopherCricketWallace
@ChristopherCricketWallace 3 жыл бұрын
good example case. confusing explanation.
@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 3 жыл бұрын
Lets see, was this a very simple example? Oh ok thought I heard that like 12 times lol
@LetsBuildThatApp
@LetsBuildThatApp 3 жыл бұрын
I am the god of simple examples.
@Gojam12
@Gojam12 3 жыл бұрын
What an oddball, I'll stick with Paul Hagerty, there is a much better way to do this.
@auronedgevicks7739
@auronedgevicks7739 2 жыл бұрын
I think a more simpler example would have worked
@finalpets
@finalpets 5 жыл бұрын
666 Likes !!!! Remove [weak self] to the like button
@user-up8fj4cp1y
@user-up8fj4cp1y 6 ай бұрын
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 2 ай бұрын
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.
How to use weak self in Swift | Continued Learning #18
20:33
Swiftful Thinking
Рет қаралды 17 М.
孩子多的烦恼?#火影忍者 #家庭 #佐助
00:31
火影忍者一家
Рет қаралды 37 МЛН
MEGA BOXES ARE BACK!!!
08:53
Brawl Stars
Рет қаралды 35 МЛН
1 or 2?🐄
00:12
Kan Andrey
Рет қаралды 33 МЛН
When to Semaphore vs Dispatch Group! Careful Multithreaded Shared Resource
11:11
Swift Closures Explained - The ONLY video you'll ever need!
17:33
Solving A Classic Google Interview Logic Puzzle
9:03
MindYourDecisions
Рет қаралды 8 МЛН
A Color Test That Can Tell Your Mental Age
7:37
BRIGHT SIDE
Рет қаралды 44 МЛН
101 Weird But Useful Minecraft Hacks
48:36
Skip the Tutorial
Рет қаралды 3,8 МЛН
12 Clear Signs You Are Actually Smart
10:03
BRIGHT SIDE
Рет қаралды 1,3 МЛН
Difference between weak and unowned in Swift
16:20
Code Cat
Рет қаралды 14 М.
Retain Cycles: How to Detect with Instruments Profiler!
13:55
Lets Build That App
Рет қаралды 48 М.
iOS Roadmap to Professional Developer: Skills you MUST have!
19:42
Lets Build That App
Рет қаралды 137 М.
孩子多的烦恼?#火影忍者 #家庭 #佐助
00:31
火影忍者一家
Рет қаралды 37 МЛН