【问题标题】:Releasing subviews发布子视图
【发布时间】:2011-05-18 11:41:13
【问题描述】:

我是 iOS 编程的新手,我正在开发的 iPad 应用程序遇到问题。 每次点击拆分视图的根视图中的单元格时,我都使用拆分视图控制器将子视图添加到拆分视图的详细视图。这很好,直到堆栈变得太高并且我的内存不足。新视图添加到堆栈后如何释放之前的子视图? 或者有没有更好的方法来解决这个问题?

谢谢

【问题讨论】:

    标签: iphone cocoa-touch uiview uiviewcontroller uisplitviewcontroller


    【解决方案1】:

    要从其父视图中删除视图:

    [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 示例中一样对待视图,可能只是为了节省一行代码并隐含内存管理而做出更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多