要从其父视图中删除视图:
[view removeFromSuperview];
superview 将在此时释放视图。因此,如果超级视图是唯一具有拥有引用的参与者,则该视图将被释放。换句话说,这个:
[superview addSubview:view];
使 superview 保留视图。所以你经常会看到这样的代码块:
view = [[ViewClass alloc] initWithFrame:frame]; // I own view
[superview addSubview:view]; // superview and I both own view
[view release]; // now only superview owns view;
// it'll be deallocated if
// superview ever relinquishes
// ownership
所以你现在有一个指向视图的指针,只要视图保留在父视图中,它就有效。因此,随后向其发布removeFromSuperview 是安全的,但在此之后使用视图显然是不安全的。视图对象将只存在于 alloc/init 和 removeFromSuperview 之间。它会在被移除时被释放。
根据正常的 Cocoa 引用计数规则,以下内容与 alloc/init 和后续版本的直接替换几乎相同:
view = [ViewClass viewWithFrame:frame]; // view is an autoreleased object;
// the autorelease pool owns it
[superview addSubview:view]; // superview now owns view also
// the autorelease pool will relinquish ownership automatically, in the future...
如果你没有手动做任何事情来影响行为,只是在正常的运行循环中,那么自动释放池中的东西在当前调用堆栈的生命周期内是安全的。在这种情况下,您可以像在手动 alloc/init 示例中一样对待视图,可能只是为了节省一行代码并隐含内存管理而做出更改。