Difference between weak and unowned in Swift

Поділитися
Вставка
  • Опубліковано 11 лип 2024
  • In this tutorial we will explore the difference between weak and unowned keyword in swift. Most of the time we use weak to avoid strong reference cycle and help automatic reference counting ARC to manage memory better. Unlike weak we also have a unowned keyword which does the same.
    But the question is when to use weak and unowned and what's the difference between the two?
    In this tutorial we will explore the difference between weak and unowned keyword in details. Given below are the chapters for today's video
    0:00 introduction
    1:38 revision of strong reference cycles
    6:39 why we need weak and unowned keyword
    7:30 weak keyword
    8:25 unowned keyword
    9:00 when to use weak and unowned keyword
    9:13 example of when to use weak keyword
    9:42 rules to use weak
    10:26 example of when to use unowned keyword
    11:56 second example of unowned
    13:09 updating demo code
    13:52 unowned arc documentation
    16:00 conclusion
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Given are the links mentioned in today's video
    iOS Cafe discord server invitation link: / discord
    Automatic reference counting video link: • Automatic reference co...
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ✅ 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...
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ############################################
    Connect with me on social media
    Instagram: codecat15
    📧: codecat15@gmail.com
    🐦: / codecat15
    Facebook: / code.cat.792
    Github: github.com/codecat15
    ###########################################
    #weakvsunowned #arcInSwift #swiftHindiTutorial

КОМЕНТАРІ • 90

  • @YogeshPateliOS
    @YogeshPateliOS 2 роки тому +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  2 роки тому +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 2 роки тому +3

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

    • @CodeCat15
      @CodeCat15  2 роки тому +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.

  • @abhishekdhiman9771
    @abhishekdhiman9771 2 роки тому +1

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

    • @CodeCat15
      @CodeCat15  2 роки тому +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 😊

  • @chetanrajauria6089
    @chetanrajauria6089 2 роки тому +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  2 роки тому

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

  • @abhaykumar3333
    @abhaykumar3333 2 роки тому

    Perfect as always👍🏼

    • @CodeCat15
      @CodeCat15  2 роки тому +1

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

  • @JunaidKhan-ny8tu
    @JunaidKhan-ny8tu 2 роки тому +2

    Your content is always amazing 🤩

    • @CodeCat15
      @CodeCat15  2 роки тому +1

      Thank you Junaid 😊

  • @Shubam0902
    @Shubam0902 2 роки тому +1

    Neat and clean !! Thanks a lot

    • @CodeCat15
      @CodeCat15  2 роки тому

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

  • @poojaraghuwanshi1914
    @poojaraghuwanshi1914 Рік тому +1

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

  • @jayprakashsharma7
    @jayprakashsharma7 2 роки тому +1

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

    • @CodeCat15
      @CodeCat15  2 роки тому +1

      You are most welcome

  • @vijayendra_t
    @vijayendra_t Рік тому +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 11 місяців тому +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.

  • @sandipkhedkar
    @sandipkhedkar 2 роки тому +1

    Bhai, As usual one more masterpiece.

    • @CodeCat15
      @CodeCat15  2 роки тому

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

  • @hotskyakash
    @hotskyakash 2 роки тому +1

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

    • @CodeCat15
      @CodeCat15  2 роки тому +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 👍

  • @prataprana2963
    @prataprana2963 2 роки тому +1

    Awesome learned alot❤️🤞

  • @shubhamnaidu4189
    @shubhamnaidu4189 2 роки тому +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  2 роки тому +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.

  • @rachitsharma8829
    @rachitsharma8829 Рік тому +1

    Very well explained .. Keep it up Ravi

    • @CodeCat15
      @CodeCat15  Рік тому

      Thank you Rachit, am glad this was helpful

  • @deepamsharma9400
    @deepamsharma9400 2 роки тому +1

    superb!

  • @pvj89
    @pvj89 2 роки тому +1

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

    • @CodeCat15
      @CodeCat15  2 роки тому +1

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

  • @hapeesingh538
    @hapeesingh538 2 роки тому +5

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

    • @CodeCat15
      @CodeCat15  2 роки тому +1

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

  • @ajaychaudhary358
    @ajaychaudhary358 2 роки тому

    Very informative

    • @CodeCat15
      @CodeCat15  2 роки тому

      Glad it was helpful 👍

  • @ranganathchenna4559
    @ranganathchenna4559 2 роки тому +1

    ☞ good explanation

  • @narendrajagne7067
    @narendrajagne7067 Рік тому +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  Рік тому

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

    • @narendrajagne7067
      @narendrajagne7067 Рік тому +1

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

  • @samisiddiqui6938
    @samisiddiqui6938 2 роки тому +1

    Nice video

    • @CodeCat15
      @CodeCat15  2 роки тому

      Thank you Sami 👨‍💻

  • @ZindalsLife
    @ZindalsLife 2 місяці тому

    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.

  • @renesanpvt6695
    @renesanpvt6695 Рік тому +1

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

    • @CodeCat15
      @CodeCat15  Рік тому

      what would you like to see in that video?

  • @shaikhrakib3247
    @shaikhrakib3247 2 роки тому +1

    👌🏻

  • @AnkitJain-zd8hv
    @AnkitJain-zd8hv 11 місяців тому +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  11 місяців тому

      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.

  • @muhammadahmedbaig5192
    @muhammadahmedbaig5192 Рік тому +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  Рік тому

      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.

  • @ranganathchenna4559
    @ranganathchenna4559 2 роки тому

    What is Static Binding and Dynamic Binding?

  • @Rahul-jf5kf
    @Rahul-jf5kf 2 роки тому +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  2 роки тому +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

  • @vikasvaish3567
    @vikasvaish3567 Рік тому +1

    Sir please make video on capture list

    • @CodeCat15
      @CodeCat15  Рік тому

      Thanks for the suggestion, I’ll work on it

  • @JunaidKhan-ny8tu
    @JunaidKhan-ny8tu 2 роки тому +2

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

    • @CodeCat15
      @CodeCat15  2 роки тому +1

      I don't think doing this would create retain cycles.

    • @JunaidKhan-ny8tu
      @JunaidKhan-ny8tu 2 роки тому +1

      @@CodeCat15 thanks

  • @yashparikh2527
    @yashparikh2527 2 роки тому +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  2 роки тому +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.

  • @pvj89
    @pvj89 2 роки тому +1

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

    • @CodeCat15
      @CodeCat15  2 роки тому +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

  • @poojaraghuwanshi4086
    @poojaraghuwanshi4086 Місяць тому +1

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

    • @CodeCat15
      @CodeCat15  26 днів тому

      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.

  • @Rahul-jf5kf
    @Rahul-jf5kf 2 роки тому +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  2 роки тому

      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 2 роки тому +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  2 роки тому

      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

  • @saikumarreddygujjula3703
    @saikumarreddygujjula3703 2 роки тому +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  2 роки тому +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.

  • @abedurai7990
    @abedurai7990 Рік тому +1

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

    • @CodeCat15
      @CodeCat15  Рік тому

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

  • @pushkerpandey9312
    @pushkerpandey9312 2 роки тому +1

    When strong refrence is used or when it is important?

    • @CodeCat15
      @CodeCat15  2 роки тому +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.

  • @pushkerpandey9312
    @pushkerpandey9312 2 роки тому +1

    Can we compare struct object and class object?

    • @CodeCat15
      @CodeCat15  2 роки тому

      Can you elaborate this please

    • @pushkerpandey9312
      @pushkerpandey9312 2 роки тому

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

  • @umarparacha653
    @umarparacha653 2 роки тому +1

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

    • @CodeCat15
      @CodeCat15  2 роки тому

      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/UA-cam-tutorial

  • @akashbhardwaj5200
    @akashbhardwaj5200 2 роки тому +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  2 роки тому

      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.

  • @md-rubel
    @md-rubel 2 роки тому +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  2 роки тому +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 2 роки тому +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  2 роки тому

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

    • @sanjaykumar-yc9dz
      @sanjaykumar-yc9dz Рік тому

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