Difference between weak and unowned in Swift

Sdílet
Vložit
  • čas přidán 26. 08. 2024

Komentáře • 90

  • @YogeshPateliOS
    @YogeshPateliOS Před 2 lety +16

    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 :-)

    • @CodeCat15
      @CodeCat15  Před 2 lety +8

      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.

  • @akhilgupta6883
    @akhilgupta6883 Před 2 lety +3

    Finished the basic playlist today, Thanks Ravi for your simple and clean explanation.

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      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.

  • @vijayendra_t
    @vijayendra_t Před rokem +3

    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.

  • @user-on7do6wy6y
    @user-on7do6wy6y Před rokem +1

    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.

  • @narendrajagne7067
    @narendrajagne7067 Před rokem +1

    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.

    • @CodeCat15
      @CodeCat15  Před rokem

      Man I miss magarpatta such an awesome place that is, I spent most of my time in Kothrud

    • @narendrajagne7067
      @narendrajagne7067 Před rokem +1

      @@CodeCat15 definitively we will have cup of coffee in magarpatta if in future you will in Pune.

  • @chetanrajauria6089
    @chetanrajauria6089 Před 2 lety +1

    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.

    • @CodeCat15
      @CodeCat15  Před 2 lety

      Hey Chetan, glad to know the channel is helpful there’s more to come from combine perspective as well in the coming weeks 😊

  • @poojaraghuwanshi1914
    @poojaraghuwanshi1914 Před rokem +1

    nice Explanation Ravi this was not cleared me before watching your video big thanks for it

  • @shubhamnaidu4189
    @shubhamnaidu4189 Před 2 lety +1

    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

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      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.

  • @ZindalsLife
    @ZindalsLife Před 3 měsíci

    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.

  • @jayprakashsharma7
    @jayprakashsharma7 Před 2 lety +1

    Very good explanation as you always focus on quality of content. Thank you sir.

  • @hapeesingh538
    @hapeesingh538 Před 2 lety +5

    Good one 👍🏻, when we can expect a detailed video on CICD (Fastlane or Bitrise)?

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      it's a part of the series that I will be working on soon.

  • @hotskyakash
    @hotskyakash Před 2 lety +1

    Wonderful and detailed explaination on complex topic Ravi. I always thought unowned only applicable inside closures.

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      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 👍

  • @akashbhardwaj5200
    @akashbhardwaj5200 Před 2 lety +2

    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

    • @CodeCat15
      @CodeCat15  Před 2 lety

      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.

  • @abhishekdhiman9771
    @abhishekdhiman9771 Před 2 lety +1

    It was an amazing explanation with suitable examples. Thank you sir.

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      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 😊

  • @pvj89
    @pvj89 Před 2 lety +1

    Really helpful video Ravi this question has confused me many times in interview

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      Now I hope you’ll be able to answer more confidently Vijay. All the best for your future interview rounds 👍

  • @rachitsharma8829
    @rachitsharma8829 Před 2 lety +1

    Very well explained .. Keep it up Ravi

    • @CodeCat15
      @CodeCat15  Před 2 lety

      Thank you Rachit, am glad this was helpful

  • @deepamsharma9400
    @deepamsharma9400 Před 2 lety +1

    superb!

  • @renesanpvt6695
    @renesanpvt6695 Před 2 lety +1

    Very good explanation , Please make video on git version control.

    • @CodeCat15
      @CodeCat15  Před 2 lety

      what would you like to see in that video?

  • @sandipkhedkar
    @sandipkhedkar Před 2 lety +1

    Bhai, As usual one more masterpiece.

    • @CodeCat15
      @CodeCat15  Před 2 lety

      Thank you Sandip, do share the video with your iOS group and feel free to ask questions :)

  • @yashparikh2527
    @yashparikh2527 Před 2 lety +2

    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

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      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.

  • @JunaidKhan-ny8tu
    @JunaidKhan-ny8tu Před 2 lety +2

    Your content is always amazing 🤩

  • @AnkitJain-zd8hv
    @AnkitJain-zd8hv Před rokem +1

    Nice explanation. I have one question should we use [weak self] or [unowned self] in API calling completion handler. In case of escaping closure

    • @CodeCat15
      @CodeCat15  Před rokem

      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.

  • @ranganathchenna4559
    @ranganathchenna4559 Před 2 lety +1

    ☞ good explanation

  • @Shubam0902
    @Shubam0902 Před 2 lety +1

    Neat and clean !! Thanks a lot

    • @CodeCat15
      @CodeCat15  Před 2 lety

      Glad this was helpful, please feel free to ask questions and do share the channel with your iOS group.

  • @prataprana2963
    @prataprana2963 Před 2 lety +1

    Awesome learned alot❤️🤞

  • @muhammadahmedbaig5192
    @muhammadahmedbaig5192 Před rokem +1

    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?

    • @CodeCat15
      @CodeCat15  Před rokem

      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.

  • @samisiddiqui6938
    @samisiddiqui6938 Před 2 lety +1

    Nice video

  • @vikasvaish3567
    @vikasvaish3567 Před 2 lety +1

    Sir please make video on capture list

    • @CodeCat15
      @CodeCat15  Před 2 lety

      Thanks for the suggestion, I’ll work on it

  • @poojaraghuwanshi4086
    @poojaraghuwanshi4086 Před 2 měsíci +1

    @ravi if unowned is always work so why we should not always use unowned , why we depends on weak???

    • @CodeCat15
      @CodeCat15  Před 2 měsíci

      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.

  • @md-rubel
    @md-rubel Před 2 lety +1

    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.

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      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

    • @md-rubel
      @md-rubel Před 2 lety +1

      @@CodeCat15 I have mailed you with sample code. please have a look into it and let me know more about this behavior.

    • @CodeCat15
      @CodeCat15  Před 2 lety

      That’s great, thank you I’ll check my mail soon.

    • @sanjaykumar-yc9dz
      @sanjaykumar-yc9dz Před 2 lety

      @@CodeCat15 As john instance is local to function in your demo, it will be deallocated after function completes execution. thanks for a great video.

  • @JunaidKhan-ny8tu
    @JunaidKhan-ny8tu Před 2 lety +2

    A question was asked in interview i.e does the alert controller create retain cycle when used in viewcontroller?

  • @Rahul-jf5kf
    @Rahul-jf5kf Před 2 lety +3

    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

    • @CodeCat15
      @CodeCat15  Před 2 lety +2

      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

  • @shaikhrakib3247
    @shaikhrakib3247 Před 2 lety +1

    👌🏻

  • @saikumarreddygujjula3703
    @saikumarreddygujjula3703 Před 2 lety +1

    Your content is fantastic, and why don't you add regional language support like Telugu, Tamil, and Kannada. If possible? I appreciate it 😊

    • @CodeCat15
      @CodeCat15  Před 2 lety +3

      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.

  • @ajaychaudhary358
    @ajaychaudhary358 Před 2 lety

    Very informative

  • @abhaykumar3333
    @abhaykumar3333 Před 2 lety

    Perfect as always👍🏼

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      Thank you so much 😀, please feel free to ask questions and do share the video with your iOS group 😊

  • @pushkerpandey9312
    @pushkerpandey9312 Před 2 lety +1

    When strong refrence is used or when it is important?

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      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.

  • @abedurai7990
    @abedurai7990 Před rokem +1

    Why are you using underscore(_) before parameter in init method

    • @CodeCat15
      @CodeCat15  Před rokem

      No specific reason, this is what I use sometimes when I am giving a demo

  • @ranganathchenna4559
    @ranganathchenna4559 Před 2 lety

    What is Static Binding and Dynamic Binding?

  • @umarparacha653
    @umarparacha653 Před 2 lety +1

    Ravi outstanding
    Please provide source code
    I am not able to download from github
    Please all swift code

    • @CodeCat15
      @CodeCat15  Před 2 lety

      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/CZcams-tutorial

  • @pvj89
    @pvj89 Před 2 lety +1

    Hi Ravi, I have question can you please tell me how optional is implemented in swift? It was interview question.

    • @CodeCat15
      @CodeCat15  Před 2 lety +1

      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

  • @Rahul-jf5kf
    @Rahul-jf5kf Před 2 lety +1

    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.

    • @CodeCat15
      @CodeCat15  Před 2 lety

      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.

    • @Rahul-jf5kf
      @Rahul-jf5kf Před 2 lety +1

      @@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.

    • @CodeCat15
      @CodeCat15  Před 2 lety

      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

  • @pushkerpandey9312
    @pushkerpandey9312 Před 2 lety +1

    Can we compare struct object and class object?

    • @CodeCat15
      @CodeCat15  Před 2 lety

      Can you elaborate this please

    • @pushkerpandey9312
      @pushkerpandey9312 Před 2 lety

      Someone asked me in the interview.. Can we ompare objects of classes and struct with '==='