whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes a strong reference to the instance. 👌🏻👌🏻👌🏻 - Great Explanation :-)
Indeed, swift by default makes a strong reference when we use reference types and hence its important to use keywords like weak and unowned based on the object relationship.
I am glad the basic playlist was helpful, please start with protocols and code like a pro playlist as they will be the foundation of writing clean code and also majority of my videos are based on SOLID principle so it’ll be a good place to start next.
If you have declared John object in viewcontorller class then you need to assign it nil, and if you have declare it in viewdidload then you don't have to assign it nil, because object goes out of scope and it will be deallocate automatically, that's why in this case you do not need to assign nil in unowned also.
Thanks for the explanation, And in your case your john object scope is limited to viewdidload but in example over swift it was a class variable. And the deinit was called once it was set to nil only.
Bro, You are damn good. I really watch all of your videos and your explanation is too good. Me and my team follow you and have learned so many things from your tutorials.
Ravi Bhai , Here in magarpatta pune raining and I am with cup of coffee while watching video ..... I really love it finally my retain cycle concepts cleared.
Had an interview last friday, and this same question was asked and i was not able to answer, I am glad that you created the video, now I am clear what unowned is and I will be able to answer this in my next interview. Thanks
I am sure in the next round you are going to answer all the questions Shubham, all the best for interviews be confident when you respond to answer, pretty sure you'll nail a good offer very soon.
I remember this request from your end on instagram and my apologies I delayed in making this video, but here it is and I am glad this was helpful to you 😊
The choice between [weak self] and [unowned self] depends on the specific situation and the potential behavior you want in case the referenced object (self) is deallocated. In the context of API calling completion handlers, [weak self] is often the safer choice, as network requests might take time to complete, and self could be deallocated before the closure finishes executing.
Hi Ravi, One question. value types get created on stack memory and class types on heap memory. now if any struct is created in controller where memory gets allocated 1) on stack as it is struct 2) on heap because struct is defined in class. if 2nd is true then for any app there structs are always allocated on heap. Is tere any way to check where memory for that instance gets allocated
This is a great question Rahul and thank you for asking this, here's what I understand and I am not sure if this is true, what I assume is when you create a property of struct type inside a class then that property points to the memory location which can be either in stack or heap. I think pointers have a role to play here but at this point this is what I assume. The above assumption is based on something that I read in the swift documentation of struct and class which states this A Swift constant or variable that refers to an instance of some reference type is similar to a pointer in C, but isn’t a direct pointer to an address in memory Documentation link: docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html
Ravi, Thanks for the great content. One Question: why do we need to use [unowned self], however, there is a chance that the "self" can be removed from memory, and (according to my understanding) as unowned can't be nil then it may lead to a crash? why people are using [unowned self] in the capture list, Is there any scenario or use case where we need to use [unowned self] in the capture list for closures?
I personally have not got into a situation where I need to use it, but it all depends on object relationships which devs don’t really care about when they create the models, depending on the object relationship I think it makes sense to use unowned where a particular object cannot and should not be nil.
Hi man Really appreciate your work, always helpful. Specially your Hindi tutorials. Swift documentation me Unowned property ko manually nil set karne waali line par me kuch explanation de sakta hu. Usually aisi condition banti nhi h par aapne video me topic discuss kiya to mera bhi interest bana to dig it little bit more & I found this:- Just in case agar aap kisi Unowned property ko optional bana dete ho to jab bhi aap us property ko access karne ki koshish karoge to aap usem koi specific value ya nil expect karoge. But in case of Optional unowned property eak third case bhi ban jata h. Run Time crash ka. So due to any reason “unowend” object out of memory chala jaat h to to ARC uske pointer me nil value assign karne ki jagah use as it is rahne deta h. Aur jab bhi aapka code property ko access karega you will get a run-time error. Check out this example: class Master{ /// Comment & uncomment the following lines respectively to see the revolution of the slaves weak var mySlave: Slave? // unowned var mySlave: Slave? init(mySlave: Slave){ self.mySlave = mySlave } deinit{ print("Master is dead") ///Just in case you decide to change my destiny } } class Slave{ var myMaster: Master? deinit{ print("Slave is dead") } } var freeSlave = Slave() let paiseWaalaaMaster = Master(mySlave: freeSlave) freeSlave.myMaster = paiseWaalaaMaster /// Just to create reference cycle like vibes ;-) By the way useless in this code. freeSlave = Slave() /// Releasing the previous slave print("Find my slave") print(paiseWaalaaMaster.mySlave) /// This is the judgment day
yes that's an edge case which we rarely see in the code but is good to know thanks for adding it here appreciate the help, mostly we will end up using weak most of the time but then using weak and unowned depends on the object relationships and using the right keyword helps.
Yes we can, it all depends on the requirements. it’ll be a little messy to explain that in comment, but I’ll surely work something up and update this thread Yash.
Choosing between weak and unowned depends on the specific relationship and lifecycle guarantees between the objects involved, weak is used for optional reference whereas unwoned is used for non-optional references. You should unowned only on those types which are never expected to be nil but if for some reason they do end up being nil then it will crash the app and hence weak should be the choice as it won't crash the app.
Hi Ravi, One more question. There is a webservice which returns a DTO(model) which has 4 fields with different data type and name. and order in which the 4 fields returns is always different. now I want show data in table in which order it is received from server.
Usually I would just display the data as I get from the server, but if the requirement is to show the sorting order in some label then I would ask the api team to return a Boolean flag called isSortedInAscending if the flag is true then it’s ascending else descending. If you want to show the sorting order with the field that’s used for the sorting like startDate or some other id, I would ask the api team to return that in the response. Remember, the API team can change the sorting order and the sorting keys anytime they want to so it’s better to get those in the response If the server team can’t give you those fields then we can’t predict such things by just looking at the response coz again the possibility is that the server team can change the order so better if they give us those keys.
@@CodeCat15 but there is no any extra filed. actual requirement is you have an online shopping app which has different cells. like product description, image, review payment. now each time user gets all these details in different order but number of fields remain same. no any other filed for identifying sequence. and we have to display it as per sequence it received from server. I told to use Json directly instead of parsing it. but he was not agree. and telling it is possible even after parsing.
Can’t you sort them by product ID? Or may be the question here is are you even receiving the product ID in the response? Pretty sure there has to be some identifiable field that’s being sent in the response, using that you may sort the data on your side for display. If there’s none then the api team has to give something with help of which you can sort the data if they deny it then I am not sure how you’ll know the sorting order. Maybe worst case you use the product name to sort data alphabetical but not sure if this matches with what you want to achieve
Optional is a enum in swift, here’s the source code from apple GitHub for optional implementation. github.com/apple/swift/blob/main/stdlib/public/core/Optional.swift
Hello Ravi, At 15:30 you said that we have to manually set object nil while using unowned, and that is true. if we do not set object nil, the deinit method will never be called. But here in your video, the deinit is called, because you have created the john object inside the viewDidLoad method; and when the viewDidLoad block exited, john object was automatically destroyed. look at the below code: var john: Customer? override func viewDidLoad() { super.viewDidLoad() john = Customer(name: "John Appleseed") john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!) john = nil } here if we do not set john = nil, the deinit will never be called. please current me if I'm wrong. by the way, thank you so much for the video.
That’s what I thought, but then this means that we don’t need to explicitly set John to nil coz it will be taken care by ARC itself, can you share an example where we are explicitly setting the object to nil and without setting the object to nil the deinit block does not execute? You can send an email of the example, would like to see that behavior in code. I did try couple of things to get the behavior working so that I could include it in the video but I guess my approach was wrong
By default swift creates strong references between two reference types, strong references are never good as they are not disposed and hence always consider using weak or unowned keyword than creating strong references.
Thank you Sai for your kind words, the best I can do is add English subtitles to the video which is a lot of work actually like for a 5 min video I would need around 1 hour time to write the captions which is fine coz then the content reaches a lot of other developers.
I have not pushed source code for this video since it was a simple one, but for all the other videos I maintain a GitHub repository the link for the same is given below github.com/codecat15/RUclips-tutorial
whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes a strong reference to the instance. 👌🏻👌🏻👌🏻 - Great Explanation :-)
Indeed, swift by default makes a strong reference when we use reference types and hence its important to use keywords like weak and unowned based on the object relationship.
Finished the basic playlist today, Thanks Ravi for your simple and clean explanation.
I am glad the basic playlist was helpful, please start with protocols and code like a pro playlist as they will be the foundation of writing clean code and also majority of my videos are based on SOLID principle so it’ll be a good place to start next.
If you have declared John object in viewcontorller class then you need to assign it nil, and if you have declare it in viewdidload then you don't have to assign it nil, because object goes out of scope and it will be deallocate automatically, that's why in this case you do not need to assign nil in unowned also.
In your use case, you don't have to set object to nil because the object went out of scope. Objects going out of scope are automatically set to nil.
nice Explanation Ravi this was not cleared me before watching your video big thanks for it
You're most welcome
Thanks for the explanation, And in your case your john object scope is limited to viewdidload but in example over swift it was a class variable. And the deinit was called once it was set to nil only.
Bro, You are damn good. I really watch all of your videos and your explanation is too good. Me and my team follow you and have learned so many things from your tutorials.
Hey Chetan, glad to know the channel is helpful there’s more to come from combine perspective as well in the coming weeks 😊
Very good explanation as you always focus on quality of content. Thank you sir.
You are most welcome
Ravi Bhai , Here in magarpatta pune raining and I am with cup of coffee while watching video ..... I really love it finally my retain cycle concepts cleared.
Man I miss magarpatta such an awesome place that is, I spent most of my time in Kothrud
@@CodeCat15 definitively we will have cup of coffee in magarpatta if in future you will in Pune.
Very well explained .. Keep it up Ravi
Thank you Rachit, am glad this was helpful
Had an interview last friday, and this same question was asked and i was not able to answer,
I am glad that you created the video, now I am clear what unowned is and I will be able to answer this in my next interview.
Thanks
I am sure in the next round you are going to answer all the questions Shubham, all the best for interviews be confident when you respond to answer, pretty sure you'll nail a good offer very soon.
It was an amazing explanation with suitable examples. Thank you sir.
I remember this request from your end on instagram and my apologies I delayed in making this video, but here it is and I am glad this was helpful to you 😊
Wonderful and detailed explaination on complex topic Ravi. I always thought unowned only applicable inside closures.
We can use it as [unowned self] just like [weak self] in a closure, all depends on the use case, I am glad this was helpful 👍
Bhai, As usual one more masterpiece.
Thank you Sandip, do share the video with your iOS group and feel free to ask questions :)
Your content is always amazing 🤩
Thank you Junaid 😊
Good one 👍🏻, when we can expect a detailed video on CICD (Fastlane or Bitrise)?
it's a part of the series that I will be working on soon.
Really helpful video Ravi this question has confused me many times in interview
Now I hope you’ll be able to answer more confidently Vijay. All the best for your future interview rounds 👍
Nice explanation. I have one question should we use [weak self] or [unowned self] in API calling completion handler. In case of escaping closure
The choice between [weak self] and [unowned self] depends on the specific situation and the potential behavior you want in case the referenced object (self) is deallocated.
In the context of API calling completion handlers, [weak self] is often the safer choice, as network requests might take time to complete, and self could be deallocated before the closure finishes executing.
Neat and clean !! Thanks a lot
Glad this was helpful, please feel free to ask questions and do share the channel with your iOS group.
A question was asked in interview i.e does the alert controller create retain cycle when used in viewcontroller?
I don't think doing this would create retain cycles.
@@CodeCat15 thanks
Hi Ravi,
One question. value types get created on stack memory and class types on heap memory.
now if any struct is created in controller where memory gets allocated
1) on stack as it is struct
2) on heap because struct is defined in class.
if 2nd is true then for any app there structs are always allocated on heap.
Is tere any way to check where memory for that instance gets allocated
This is a great question Rahul and thank you for asking this, here's what I understand and I am not sure if this is true,
what I assume is when you create a property of struct type inside a class then that property points to the memory location which can be either in stack or heap.
I think pointers have a role to play here but at this point this is what I assume.
The above assumption is based on something that I read in the swift documentation of struct and class which states this
A Swift constant or variable that refers to an instance of some reference type is similar to a pointer in C, but isn’t a direct pointer to an address in memory
Documentation link: docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html
Ravi,
Thanks for the great content.
One Question: why do we need to use [unowned self], however, there is a chance that the "self" can be removed from memory, and (according to my understanding) as unowned can't be nil then it may lead to a crash? why people are using [unowned self] in the capture list, Is there any scenario or use case where we need to use [unowned self] in the capture list for closures?
I personally have not got into a situation where I need to use it, but it all depends on object relationships which devs don’t really care about when they create the models, depending on the object relationship I think it makes sense to use unowned where a particular object cannot and should not be nil.
Very good explanation , Please make video on git version control.
what would you like to see in that video?
Awesome learned alot❤️🤞
Thank you Pratap 👍
Hi man
Really appreciate your work, always helpful. Specially your Hindi tutorials.
Swift documentation me Unowned property ko manually nil set karne waali line par me kuch explanation de sakta hu.
Usually aisi condition banti nhi h par aapne video me topic discuss kiya to mera bhi interest bana to dig it little bit more & I found this:-
Just in case agar aap kisi Unowned property ko optional bana dete ho to jab bhi aap us property ko access karne ki koshish karoge to aap usem koi specific value ya nil expect karoge. But in case of Optional unowned property eak third case bhi ban jata h. Run Time crash ka. So due to any reason “unowend” object out of memory chala jaat h to to ARC uske pointer me nil value assign karne ki jagah use as it is rahne deta h. Aur jab bhi aapka code property ko access karega you will get a run-time error.
Check out this example:
class Master{
/// Comment & uncomment the following lines respectively to see the revolution of the slaves
weak var mySlave: Slave?
// unowned var mySlave: Slave?
init(mySlave: Slave){
self.mySlave = mySlave
}
deinit{
print("Master is dead") ///Just in case you decide to change my destiny
}
}
class Slave{
var myMaster: Master?
deinit{
print("Slave is dead")
}
}
var freeSlave = Slave()
let paiseWaalaaMaster = Master(mySlave: freeSlave)
freeSlave.myMaster = paiseWaalaaMaster /// Just to create reference cycle like vibes ;-) By the way useless in this code.
freeSlave = Slave() /// Releasing the previous slave
print("Find my slave")
print(paiseWaalaaMaster.mySlave) /// This is the judgment day
yes that's an edge case which we rarely see in the code but is good to know thanks for adding it here appreciate the help, mostly we will end up using weak most of the time but then using weak and unowned depends on the object relationships and using the right keyword helps.
Hii Ravi
Learn many things in video.
Can you please add comment for.
Can we use unowned in closure?
If yes then explain in short example
Yes we can, it all depends on the requirements.
it’ll be a little messy to explain that in comment, but I’ll surely work something up and update this thread Yash.
@ravi if unowned is always work so why we should not always use unowned , why we depends on weak???
Choosing between weak and unowned depends on the specific relationship and lifecycle guarantees between the objects involved, weak is used for optional reference whereas unwoned is used for non-optional references. You should unowned only on those types which are never expected to be nil but if for some reason they do end up being nil then it will crash the app and hence weak should be the choice as it won't crash the app.
superb!
Thank you 😊
Hi Ravi,
One more question.
There is a webservice which returns a DTO(model) which has 4 fields with different data type and name. and order in which the 4 fields returns is always different. now I want show data in table in which order it is received from server.
Usually I would just display the data as I get from the server, but if the requirement is to show the sorting order in some label then I would ask the api team to return a Boolean flag called isSortedInAscending if the flag is true then it’s ascending else descending.
If you want to show the sorting order with the field that’s used for the sorting like startDate or some other id, I would ask the api team to return that in the response.
Remember, the API team can change the sorting order and the sorting keys anytime they want to so it’s better to get those in the response
If the server team can’t give you those fields then we can’t predict such things by just looking at the response coz again the possibility is that the server team can change the order so better if they give us those keys.
@@CodeCat15 but there is no any extra filed.
actual requirement is you have an online shopping app which has different cells. like product description, image, review payment.
now each time user gets all these details in different order but number of fields remain same. no any other filed for identifying sequence. and we have to display it as per sequence it received from server.
I told to use Json directly instead of parsing it. but he was not agree. and telling it is possible even after parsing.
Can’t you sort them by product ID? Or may be the question here is are you even receiving the product ID in the response?
Pretty sure there has to be some identifiable field that’s being sent in the response, using that you may sort the data on your side for display.
If there’s none then the api team has to give something with help of which you can sort the data if they deny it then I am not sure how you’ll know the sorting order.
Maybe worst case you use the product name to sort data alphabetical but not sure if this matches with what you want to achieve
Perfect as always👍🏼
Thank you so much 😀, please feel free to ask questions and do share the video with your iOS group 😊
Hi Ravi, I have question can you please tell me how optional is implemented in swift? It was interview question.
Optional is a enum in swift, here’s the source code from apple GitHub for optional implementation.
github.com/apple/swift/blob/main/stdlib/public/core/Optional.swift
☞ good explanation
Thank you 😊
Hello Ravi,
At 15:30 you said that we have to manually set object nil while using unowned, and that is true. if we do not set object nil, the deinit method will never be called.
But here in your video, the deinit is called, because you have created the john object inside the viewDidLoad method; and when the viewDidLoad block exited, john object was automatically destroyed. look at the below code:
var john: Customer?
override func viewDidLoad() {
super.viewDidLoad()
john = Customer(name: "John Appleseed")
john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)
john = nil
}
here if we do not set john = nil, the deinit will never be called. please current me if I'm wrong.
by the way, thank you so much for the video.
That’s what I thought, but then this means that we don’t need to explicitly set John to nil coz it will be taken care by ARC itself,
can you share an example where we are explicitly setting the object to nil and without setting the object to nil the deinit block does not execute?
You can send an email of the example, would like to see that behavior in code.
I did try couple of things to get the behavior working so that I could include it in the video but I guess my approach was wrong
@@CodeCat15 I have mailed you with sample code. please have a look into it and let me know more about this behavior.
That’s great, thank you I’ll check my mail soon.
@@CodeCat15 As john instance is local to function in your demo, it will be deallocated after function completes execution. thanks for a great video.
Why are you using underscore(_) before parameter in init method
No specific reason, this is what I use sometimes when I am giving a demo
Sir please make video on capture list
Thanks for the suggestion, I’ll work on it
When strong refrence is used or when it is important?
By default swift creates strong references between two reference types, strong references are never good as they are not disposed and hence always consider using weak or unowned keyword than creating strong references.
Very informative
Glad it was helpful 👍
What is Static Binding and Dynamic Binding?
Nice video
Thank you Sami 👨💻
Can we compare struct object and class object?
Can you elaborate this please
Someone asked me in the interview.. Can we ompare objects of classes and struct with '==='
Your content is fantastic, and why don't you add regional language support like Telugu, Tamil, and Kannada. If possible? I appreciate it 😊
Thank you Sai for your kind words, the best I can do is add English subtitles to the video which is a lot of work actually like for a 5 min video I would need around 1 hour time to write the captions which is fine coz then the content reaches a lot of other developers.
Ravi outstanding
Please provide source code
I am not able to download from github
Please all swift code
I have not pushed source code for this video since it was a simple one, but for all the other videos I maintain a GitHub repository the link for the same is given below
github.com/codecat15/RUclips-tutorial
👌🏻
👍 ✌️