Search code examples
iphoneviewsubviewretain

(iphone) what happens to subviews when superview is dealloced?


Suppose a view(A) has subviews. The view(A) is getting dealloced because its retain count goes zero.

What happens to the subviews of view(A)?
Do they get detached(removed from view A) and their retain count decrease accordingly?

Thank you


Solution

  • Assuming by 'view' you actually mean 'instance of UIView':

    Views retain their subviews, and therefor, if a view gets deallocated, it's subviews get released and their retain count decreases by one.

    I'm not sure, but I guess the view hierarchy is implemented like this:

    @interface UIView : UIResponder {
      NSArray *_subviews;
    }
    
    @property(nonatomic, retain) NSArray *subviews;
    
    @end
    
    @implementation UIView
    @synthesize subviews;
    - (void)dealloc {
      [subviews release];
      [super dealloc];
    }
    @end
    

    You can roughly say that NSObject declares an unsigned integer which is the retain count, like this:

    unsigned retainCount;
    

    Then, these would be the implementations of -[id<NSObject> retain] and -[id<NSObject> release]:

    - (void)retain {
      retainCount++;
    }
    
    - (void)release {
      retainCount--;
      if (retainCount == 0) {
        [self dealloc];
      }
    }