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];
}
}
All subviews will be released.
If the main view is released or deallocated then all the child view inside it will also be deallocated
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.
精彩评论