简体   繁体   English

(iphone)取消分配超级视图后,子视图会怎样?

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

Suppose a view(A) has subviews. 假设一个视图(A)具有子视图。 The view(A) is getting dealloced because its retain count goes zero. 由于其保留计数为零,因此视图(A)正在被释放。

What happens to the subviews of view(A)? 视图(A)的子视图会怎样?
Do they get detached(removed from view A) and their retain count decrease accordingly? 它们是否分离(从视图A中移出)并且保留数相应减少?

Thank you 谢谢

Assuming by 'view' you actually mean 'instance of UIView': 假设“视图”实际上是指“ 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: 您可以粗略地说NSObject声明了一个无符号整数,即保留计数,如下所示:

unsigned retainCount;

Then, these would be the implementations of -[id<NSObject> retain] and -[id<NSObject> release] : 然后,这些将是-[id<NSObject> retain]-[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. 超级视图的取消分配将调用子视图的removeFromSuperview ,然后调用子视图的willMoveToSuperview以“告知其超级视图将要更改为指定超级视图的视图。”在这种情况下,将被取消分配。

Setting a debug point in subview's willMoveToSuperview can verify this easily. 在子视图的willMoveToSuperview中设置调试点可以轻松验证这一点。

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. 因此,如果子视图是kvo superview的属性,那么在这里是removeObserver的好地方,因为如果我们这样做,子视图dealloc(稍后将被调用)已经为时已晚。 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. 我们将得到类似“ NSInternalInconsistencyException”之类的异常,原因是:“ UITableView类的实例0x135a9a600被释放,而键值观察器仍在其中注册。

所有子视图将被释放。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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