Automatic reference counting | What is swift ARC | Memory management in swift
Вставка
- Опубліковано 18 січ 2020
- ARC in swift or automatic reference counting in swift is a key topic in swift memory management, In this swift tutorial, we learn how we programmers end up creating a strong reference cycle in the application and how we can break it using weak reference in swift.
Swift uses ARC technique to manage the memory but sometimes it’s also how we write our code that dictates if swift ARC will keep the object in memory or will remove it.
What is ARC in swift, OR a common interview question that’s always being asked so I hope with this video we learn better to answer this question?
In this swift tutorial on ARC and memory management, I will explain how we can write code to avoid a strong reference cycle which will help us to clean up unwanted objects from the memory immediately if they are not being used anymore.
Using the deinit keyword in swift we can keep track if the object was released or ended up in a strong reference cycle, in many case I just use the weak keyword in swift to avoid strong reference cycles because it’s easier that way.
Let me know if you have used deinit in some scenarios it will be interesting to hear your use case.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
✅ Subscribe to the channel and stay ahead of everyone by following the right way for writing clean code in swift. 🔥🔥🔥🔥🔥
🔗Click on the link to subscribe: ua-cam.com/users/codecat?sub...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
🎶 Royalty free Music: www.bensound.com
-----------------------------------------------------------------------------------------------------------------------
📥 Download the code from the given link
Google drive link: drive.google.com/open?id=1z8B...
Github link: github.com/codecat15/UA-cam-...
-----------------------------------------------------------------------------------------------------------------------
############################################
Connect with me on social media
📧: codecat15@gmail.com
#️⃣: / codecat15
Facebook: / code.cat.792
Github: github.com/codecat15
###########################################
#swiftDev #swiftiOS #arcInSwift
ARC in Swift OR Automatic reference counting in swift is one term that swift developers be it beginners or experienced will always come across, this video will show you a practical demo of how ARC works in Swift. So do check the video till the end and do share it with your iOS group on WhatsApp or Facebook and always feel free to ask questions
Yes, every developer should know the significance of memory management.
Great explanation.!
Thank you Puneet, I am glad you liked the video. Let me know if you have any questions on this topic will be happy to answer them.
best best best ever... explanation thanks..
perfect video hai vai
It's really help full for me. Thank u so much ✨
Thank you, am glad this was helpful
Outstanding explanation !!
Thankyou so much 😇
Thanks a lot Shivani, let me know if you have any questions on this topic will be happy to answer those. Also do subscribe to the channel and share it with your iOS group.
Nicely explained! Thanks.
Glad it was helpful!
These videos are amazing, Thanks for them
Glad you think so!
To the point man! thanks alot for the info
Welcome to the channel Dhruvil, i am glad this video was helpful to you, please feel free to ask any questions on this topic and do share this video with your iOS group on WhatsApp or Facebook
thank u very much
I learn always new things every time from your videos. Very nice explanation with real time examples..
Happy to hear that Kapil :)
easily understood, thanks bro!
Glad it helped
this is something I was searching for
I am glad your search ended here, feel free to ask questions on this topic
Best explains easily understand thank you
Glad to hear that Vipul 😀
Thank you very much brother. By watching your video I came to know the importance of strong and weak reference in ARC management. 🤝🤝🤝🤝
I am glad it was helpful, You may also want to watch a video called as weak vs unowned which was released few weeks back as that too caries good information in terms of memory management and how ARC works. Here's the link to the video
Weak vs unowned: ua-cam.com/video/HdhJjc7Y6iw/v-deo.html
You are awesome
Nice Explanation
Thanks and welcome
More and More helpful......tomorrow in my interview.....now clearly understood ARC......Thanks Man !!!
Hello Deepak welcome to the channel,
All the best for the interview buddy, also have a look at any and anyobject video i got some feedback that it’s a hot topic for interviews.
Am glad this video was helpful if you have any more questions then please feel free to ask and do share good news soon all the best once again 👍
@@CodeCat15 Yes....i have watched that one 😊....you decorate the content in this way.... That is really helpful for me 😉
Am glad it helps Deepak 😊
you are a Gem
Thank you for the kind words
thanks 🙏
Welcome
Thanks Ravi
Welcome :)
I got it :-) I have question and does the creating alertViewController and its action handler creates strong reference to current ViewController in which it is called? Thanks for such great video
Thanks bro
No problem, if you have any questions please feel free to ask and do share this with your iOS group
Hello ravi,
please explain weak and unowned difference
Tnk u sa...🤗🤗🤗 kitna achha explain kiya aapne..
You are welcome 🙏, koi questions hoga is topic pe to plz puchna will be happy to answer it, aur plz do subscribe and aapne iOS group mai bhi share karna is video ko
@@CodeCat15 of course sa...
good explanation
Thank you
Hey CodeCat, Good to know How we can use weak to break a cycle,I have a question on the ARC, What if Person refers to Job and if Job refers to some another class and that third-class again refer a person class. And again Job class has two objects refer to a person and third class. In that case what ARC do and How to calculate retain count of an object?
@Tushar: Let's divide the answer into two parts
1. The first part of your question deals with a nested object relationship and is usually a common case in CRM or any social media projects. Given below is the sample relationship I came up with as per your first part of the question
Person -> Job
Job -> Team
Job -> Person
Team -> Person
In this case, we can see person object is used by 2 references "Team" and "Job", so we have a strong reference of person so just declaring person as weak in "Team" class is not enough you have to declare person as weak property in both "Team" and "Job" class to break the strong reference cycle.
In cases like these, we have to take a step back and think about the reference cycle and carefully declare properties with the weak keyword if we want to take advantage of swift ARC else if you just declare them without weak keyword then your memory will just be filled up with all these objects which are not even used and your application may be impacted by this.
2. Even if you know that the retain count of a class is 2 or 3 then my question to you is what are you going to do with that information?
If you just declare the property with weak keyword then, in this case, you don't have to worry about the retain count. I remember the days when I was coding in Objective C and C++ where I had to nil the objects I create but with swift ARC all of this is done for you but given the condition, your code meets the requirements of ARC as shown in the tutorial.
If swift finds out your code is having a strong reference to some object then that object will NOT be deallocated from the memory so code wisely and avoid the trap of strong reference cycles.
I hope I was able to answer your question, if you have any other doubts with regards to memory management then please feel free to ask I will be happy to answer it.
Please make video for instruments and profiling
Very informative video. Please make a detailed video on how to use strong weak copy retain. Difference between strong weak copy retain.
Hey Swati, welcome to the channel and thank you for your comment I surely will make a video on the mentioned topic
@@CodeCat15 thank you so much. Your videos are very helpful and you make it really easy to understand
I am glad the vides are helpful Swati, feel free to ask questions and do share the channel with your iOS group on WhatsApp or Facebook 😊
Hello sir,
What is difference between reference count and retain count?
Make a video for ABI Stability new feature of swift 5 what does it means in actual Please
Simple & easy way to explain. 1. Can you please explain how unowned work. 2. How we use weak or unowned in closure.
Hey there welcome to the channel and thank you for your comments. Thank you for your request i will work on it and if you have any questions on this topic then plz do feel free to ask and do share this with your iOS group. Btw I recently released a video on closures covering few more details in closures, check it out if you like here’s the link for the same
closures part 2: ua-cam.com/video/ZP4pEHtndFE/v-deo.html
@@CodeCat15 sure , I will definitely look
Hi Ravi, i really liked your videos and the way you are doing this. I have a question, when does ARC run? LIke is there any timeinterval or what?
Hey there @Kapil, welcome to the channel and thank you for asking this question. The short answer is there are no time interval, so now the question comes what's triggering ARC then? How does it take care of objects which are not in use and here's the long answer.
When you create an object, memory is allocated to the object, ARC keeps a track about that memory location say an Object Car is stored in memory location A. Now if car object is no longer needed then ARC would clean up that memory so that it can be used for other purposes by your app, but as you see in the video if an object is still being used by another object then ARC won't touch it
Example: The object car is used by another object driver, in this case both of these objects are using each other and are changing the states of each other so in this case ARC cannot do anything.
But say someone wrote a code where the car is being used by a driver and someone deallocates the driver tell me what will happen? As seen in the action movies a car is moving and someone deallocates (shoots) the driver in programming terms driver = nil. You get to see an accident and a very bad one.
I think internally it all boils down to the reference count if the reference count of car is 0 then clean it's memory location mostly i believe this is what triggers ARC and sometimes in our code we have nested dependencies and due to which ARC can't really do anything until you kill the app so have to be smart about such use-cases and code accordingly because as you have seen in the video ARC will no deallocate if you are using the object as it tracks it.
Hope this answers your question, If not then please feel free to ask more. Do subscribe and share this video with your iOS group if it helps in clearing the concept of ARC would appreciate it.
@@CodeCat15 Thanks
No problem @Kapil, do ask more questions if you have on this I will be happy to answer them
How to make a reference live outside a method? Even though the references we create inside a method are strong, the Deinitializers is anyway called once the method exits. How to overcome this?
Hello,
I have some questions:
1. If I set my view controller global variable weak keyword then is that creating any problem ?
2. let in view controller B has a variable test. now I calling view controller B from view controller A & passing some data by test. so may I set weak keyword in test variable ?
Nice Explanation Ravi .... 🙂
I have question here,
I have to found retain count for both objects and for this i have used CFgetRetainCount method but it is giving me wrong result. check below example
class Company {
var name: String
init(name: String) { self.name = name }
deinit {
print("Deinit Called for Company")
}
}
var compnayObj = Company(name: "Rachit")
var obj1 = compnayObj
var obj2 = compnayObj
print(CFGetRetainCount(compnayObj))
// Here retain count for compnayObj is 4, Why is it 4 that confuse me.
Can you please help me on that. How can check retain count ?
Can you explain things on Weak Unowned also ?? And an explanation of why to use unowned or weak inside closures?
I will make a video on this as the explanation is a little longer for all of these and cannot type that much so apologies for the inconvenience for now 😊
Code Cat I have made a note where in case if you forget any topic that I have been commenting I’ll comment them again in some other video just as a reminder for you and as I’ll be waiting for those videos too 😅
Hahahahah sure cheers to that 🍻
Hi Ravi, this was awesome video but I have a question. We all know that ARC is compile time but how ARC manage memory management in compile time ? can you please explain?
the allocation and deallocation of objects happens at runtime because only when you run the app, memory is allocated to your objects and later is cleaned up by ARC.
So that makes ARC a runtime feature, now yes I agree that sometimes the swift compiler warns us about potential leaks but that’s only when the developer is doing something crazy with the code.
Let me know if that answers your question and if not please do ask more.
@@CodeCat15 i somehow agree with your answer but still I have some confusion.
So can we say ARC is a runtime feature?
But according to some articles, ARC adds retain and release method or adds deallocation or deinit method at the time of object creation. which makes this compile time.
So can you please make me clear on this topic?
Thanks
Is there any video explaining about unknown and weak concepts?
Hey Anushree welcome to the channel, I don’t have any dedicated videos on those but i did explain partially what weak is in the delegate video, but i think it will add more value if i make a dedicated ones for those topics. Please do feel free to ask questions and do share the channel with your iOS group on WhatsApp or Facebook
i have watched your another video, i guess which you said this is happening recursion, now you are saying this is strong cycle reference. can you please explain the differences between with same example
recursion and strong reference cycle are two different concepts, and I think i won't be able to explain the minor details in a comment but let me try, consider a 1 liter bucket, you cannot fill that bucket with more than 1 liter of liquid and we all know what happens if you try to add more than 1 liter water in the bucket it overflows which is what we saw in the recursion video in the case of recursion video what happened is the objects kept on getting created until they reached a point where there was no memory for the new objects and we got a crash so the real culprit was our code which kept on creating objects and it had nothing to do with strong reference cycles
In case of this video, you can see an object stays in the memory if any other object is still pointing to it, which tells ARC not to remove that object from the memory, I think by default such object chaining is always strong until we use keywords like weak or unowned, hope that answers your question and if not please do ask more I will be happy to answer them
Hello Ravi ,
One of interviewer ask me about security management & multiple app communication in swift what is that , can you please help me out
Hello Pooja, in iOS security management can mean a lot depending on what we are trying to protect, and can you elaborate on the multiple app communication part?
Hello sir, My question is should we need to declare every object weak? Means suppose normally I am declaring any string-type object so should we declare it with a weak keyword?
not every object but just reference types, such as class or class type protocols those should be weak. Hope that answers your question if not please ask more questions, other than weak we have one more keyword to manage memory which is unowned and a comparison of both is shown in the video given below.
Weak vs unowned: ua-cam.com/video/HdhJjc7Y6iw/v-deo.html
please explain in details strong, weak read, copy assign
reference count as well
sure those are good topics considering they are most commonly asked during interviews so sure I will note them down and will make a detailed video on them, thanks for suggesting them Sushma
Hello, I got one question during one of my interviews that like In Java, JVM will be install for memory management, how do we need to install lARC for memory management or how ARC will be available to do the same? , is it a separate component?
no need to install anything separately, it comes within the xcode environment for your project
Thank you :)@@CodeCat15
Ravi, Is this code only for reference or it's downloadable??
Hello Hareesh, welcome to the channel. The code is downloadable you may choose to download the code from GitHub or Google Drive, the link for the same is mentioned in the video description. If you have any questions then please feel free to ask and do subscribe and share this video with your iOS group on WhatsApp or Facebook
Is arc a runtime or compile time?please justify the answer
Short answer its a runtime feature.
At compile time the swift compiler will only validate the syntax of your code, objects are created and destroyed at runtime and based on how you write the code if there are no strong references ARC will do the necessary clean up.
As shown in the video if you write code which creates a strong reference cycle ARC will not destroy that object coz it thinks you are still using it and hence its the responsibility of the developer to use weak keyword whenever possible.
Can u please help me for this issue wht i forgot
Sure can, as said in the previous comment do send me out the code snippet or maybe the project if you can on GitHub and I will check it out, or if its something you can make it up on the playground then email me the playground file on my email address
What is difference between unowned and optional unowned?
video on that coming soon after the threading series
I using dinit a project but it thro me crash when dinit calling
Send me the code over email, do mention exactly where the issue is and is it a project code or playground code? If its playground then send me at my email codecat15@gmail.com else tag me on GitHub if you can share it on GitHub
I working on exist project thay are using rx swift i just create demo to saprate the functionality how to use api with moya and rx swift pattran and initlized it with router and services bt not understanding why it throwing me error i dnt send project because i create it office bt if i trying at home i will definitely send you i used 1st time rx swift and moya there are alot of thing
@@ankitarana3551 Alamofire is a wrapper around URLSession, MOYA is a wrapper around Alamofire, any reasons why you cannot use URLSession direct? Maybe a question to the senior architects who approved the use of MOYA, I think people should not use RxSwift unless there's a pretty SOLID reason as to what they are achieving using RxSwift. Sometimes adding third party code or a framework like RxSwift is not required at all but still, some developers add this to overcomplicate a simple project OR just to act cool or add technology on their Linkedin profile or resume. Do send me out your project via email or GitHub my social details are present in every video description :)
I had one question why are iboutlets declared with weak??
I am listening tell me what’s the question
@@CodeCat15 why are iboutlets marked with weak??
How do they impact the retain cycle or ARC?
The only reason why iboutlets are defaulted to memory management is because once the view controller finishes its life cycle it frees up the memory accommodated by those objects and hence the default of outlets is weak and not strong.
Once swift knows that a vc is no longer in use it will just clean up the memory used by that vc but if you have a strong reference to that vc or any outlet has a strong reference swift won’t release it as it would still think that this object is being used.
The example more or less is similar to what i have shown in the video, add a deinit keyword in your vc and add a debugprint message you should be able to see the difference.
Memory management is amazing and swift does a decent job in clearing up things but everything boils down to one single fact, how you write your code.
Let me know if this answers your question if not then just ask again buddy.
Code Cat understood sir.
Thanks
difference between weak n optional var
noted and will release a video soon
hi please upload in english separately, concept are very good !!!
Hey Vinoth, welcome to the channel, I would surely love to do that but then most of my viewers want me to keep on making videos in Hindi, I apologize if the language has caused any inconvenience for you, please do feel free to ask questions if you have missed something because of the language I will be happy to help
@@CodeCat15 i have to learn Hindi 😄😄.!!!
Are you right now?
I am ok, had cold as the temperature went down but now I am feeling much better. Thanks for asking buddy 😊
Hi, Code Cat I understood the concept, I understood the difference between weak and unowned as well but I have 2 doubts.
1. If 2 create retain cycle then which one should be marked as weak.
2. If 2 create retain cycle then which one should be marked as unowned.
It would be helpful if. you can answer this.
Please use the Hindi title when you speak Hindi in the video...
ARC ko manage kaun karta hain bhai?
iOS system khud manage karta hai
@@CodeCat15 Thanks Ravi