UIView cleanup best practices?

Discussion in 'Public Game Developers Forum' started by lithiastudios, Apr 30, 2009.

  1. lithiastudios

    lithiastudios Well-Known Member

    Jan 9, 2009
    101
    0
    0
    Let's say I've added a UIView and then added multiple subviews to that view. From a cleanup perspective, do I need to bother calling removeFromSuperview on the subviews, or is just removing the parent view good enough?

    I realize that I'd need to release any alloc'ed subviews to free up memory, just not sure if there's any other cleanup I'd need to do if I removed the views from the scene.

    thanks!
     
  2. luis

    luis Member

    #2 luis, Apr 30, 2009
    Last edited: Apr 30, 2009
    When a view reference count gets to 0, it's dealloc method is called which does one release for each subview (the reference count of each subview decreases by one). If no other object holds a reference to the subviews, then their reference count will become 0 and their dealloc method will be called.

    Calling removeFromSuperview decrements the reference count by one because the parent releases it reference to it. If no other object holds a reference to the subview, then its reference count will become 0 and its dealloc method will be called.

    The net effect is the same:

    Operation Ref Ref
    Delta Count
    ------------------------------
    a = [UIView alloc] ++a a=1
    b = [UIView alloc] ++b b=1
    [b addSubview:a] ++a a=2
    [a release] --a a=1
    :
    :
    [b release] --b b=0 -> [b dealloc] --a a=0 -> [a dealloc]

    Operation Ref Ref
    Delta Count
    ------------------------------
    a = [UIView alloc] ++a a=1
    b = [UIView alloc] ++b b=1
    [b addSubview:a] ++a a=2
    [a release] --a a=1
    :
    :
    [a removeFromSuperview] --a a=0 -> [a dealloc]
    [b release] --b b=0 -> [b dealloc]
     
  3. haqu

    haqu Active Member

    Jan 1, 2009
    32
    0
    0
    You need to call removeFromSuperview for each subview. Just removing parent isn't enough. When you remove subview from superview it is also released automatically.
     

Share This Page