A question about Memory Management?

Discussion in 'iOS Programming' started by kexu, Oct 14, 2011.

  1. kexu macrumors newbie

    Joined:
    Oct 14, 2011
    #1
    I am reading a book on iOS programming (specifically, iOS Programming: The Big Ranch Guide, 2nd edition, page 69 if you have it).

    The author shows an example where we override the dealloc function so that we can release the instance variables. After releasing the instance variables, there is a final line that reads:

    [super dealloc];

    Why does it deallocate super? Why would it not deallocate self?

    I thought self referred to the instance and super referred to its superclass. If you add a subclass to NSObject called Thingamabob, and you declared a method for Thingamabob which read

    [self dealloc]

    what's the difference? What would that deallocate?
     
  2. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
    #2
    You are already in [self dealloc] at that point. Of course, you didn't call it yourself to get there: it was called automatically when the object's retain count hit 0. You need to call [super dealloc] to cascade the dealloc process up the class hierarchy, which ensures that any object variables that are declared in parent classes are also properly released.
     
  3. kexu thread starter macrumors newbie

    Joined:
    Oct 14, 2011
    #3
    Sorry I still don't get it.

    Are you saying that [super dealloc] is deallocating its parent class? Like is Thingamabob's [super dealloc] deallocating NSObject?
     
  4. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #4
    No, it's not deallocating its parent class. It's calling the dealloc method of the parent class.
     
  5. kexu thread starter macrumors newbie

    Joined:
    Oct 14, 2011
    #5
    I feel really stupid. What is the "parent class" in this situation?
     
  6. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #6
    If Thingamabob is a subclass of NSObject, then NSObject is the parent/super class.
     
  7. ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #7
    You call [super dealloc] inside of your subclasses's dealloc so that anything the parent class sets up will also be released. It's just like calling [super init] inside of your own init methods, to make sure all the benefits of having the superclass are bestowed on your class.
     

Share This Page