删除dealloc中的所有子视图?
问题描述:
我目前的理解是,超级视图保留了每个子视图。对于UIView的子类,我是否需要从它们的超级视图中删除所有子视图作为dealloc的一部分?我目前只是发布我的IBOutlets,删除观察到的通知,并清理任何烦人的ivars。删除dealloc中的所有子视图?
或者是删除和释放子视图的一部分UIView的[超dealloc]?
答
UIView保留其子视图,所以它负责释放它们。你的子类不拥有这些视图(除非你明确地保留它们),所以你不需要担心释放它们。
所以这听起来像你做的是正确的事情。
答
作为视图dealloc的一部分,子视图会自动删除。所以你不需要删除它们。但是,如果您的视图保留了任何子视图(除了自动保留),您应该在dealloc期间释放它们。
因此,例如,假设您的视图包含下面的代码:
[头文件]
UILabel *myLabel;
@property (nonatomic, retain) UILabel *myLabel;
[实现文件]
someLabel = [[UILabel alloc]initWithFrame: someFrame];
[self addSubview: someLabel];
self.myLabel = someLabel;
[someLabel release]; // now retained twice, once by the property and once as a subview
someButton = [[UIButton alloc]initWithFrame: someOtherFrame];
[self addSubview: someButton];
[someButton release]; // retained once as it is a subview
那么你的dealloc方法是这样的:
- (void) dealloc {
[myLabel release];
[super dealloc];
}