简体   繁体   中英

(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

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];
  }
}

The superview's dealloc will call into subviews' removedFromSuperview , then into subviews' willMoveToSuperview to "Tells the view that its superview is about to change to the specified superview.", in this case about to be dealloced.

Setting a debug point in subview's willMoveToSuperview can verify this easily.

So if subviews kvo superview's property, here is good place to removeObserver because if we do it subviews dealloc, which will be called later, it is already too late. We will get be exception like, 'NSInternalInconsistencyException', reason: 'An instance 0x135a9a600 of class UITableView was deallocated while key value observers were still registered with it.

所有子视图将被释放。

如果主视图被释放或释放,则其内部的所有子视图也将被释放

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM