【问题标题】:UIViewController memory managementUIViewController 内存管理
【发布时间】:2011-02-19 00:06:03
【问题描述】:

您好,我的 UIViewController(或我创建的任何其他对象)有一个非常基本的内存管理问题; 问题是在 Instruments 中我的对象分配图总是在上升,即使我调用 release 然后将它们分配为零。

我有 2 个 UIViewController 子类,每个子类都使用 NIB 进行初始化; 我将第一个 ViewController 添加到主窗口,例如 [window addSubView:first.view]; 然后在我的第一个 ViewController nib 文件中,我有一个加载第二个 ViewController 的按钮,例如:

-(IBAction)loadSecondView{
     if(second!=nil){ //second is set as an iVar and @property (nonatomic, retain)ViewController2* second; 
         [second release];
         second=nil;
     }
     second=[[ViewController2 alloc]initWithNibName:@"ViewController2" bundle:nil];
     [self.view addSubView:second.view];

}

在我的(第二个)ViewController2 中,我有一个带有操作方法的按钮

-(IBAction) removeSecond{

    [self.view removeFromSuperView];
}

请让我知道上述方案是否以托管方式用于内存...? 在 Instruments 中它不显示任何分配的释放,并保持条形状态图不断上升。

【问题讨论】:

    标签: iphone cocoa-touch memory-management memory-leaks uiviewcontroller


    【解决方案1】:

    首先,为什么要在 second 是一个属性时使用这个方案:

    if(second!=nil){
         [second release];
         second=nil;
     }
     second=[[ViewController2* second]initWithNibName:@"ViewController2" bundle:nil];
    

    使用 setter 时,属性会自动释放它的旧值。所以这可以重写为:

    if(self.second == nil) { //Prevents creating a new controller if there already is one.
         self.second = [[[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil] autorelease];
    }
    

    另外,[ViewController2* second] 怎么了? 为什么会有那个星号,类方法second 是做什么的?

    【讨论】:

    • 对不起,这只是一个 alloc 调用....我错过了键入它....感谢您的建议...如果我错了,请纠正我,但我从你的理论中了解到的是,如果我继续将 iVAr 集分配为属性,它会自行释放先前的分配?
    • 是的,当调用 setter 时,属性将始终(afaik)释放它的先前值。当您将属性定义为(retain) 时,它将释放旧对象,并保留新对象。但请注意:执行此操作时:self.someStringProperty = [[NSString alloc] init],该属性将保留新值,因此您的保留计数为 2。 self.someStringProperty = [[[NSString alloc] init] autorelease] 会阻止这种情况发生。
    • 好的,我尝试了你的建议,但是 if(self.second != nil) { //如果已经有一个控制器,则阻止创建新控制器。 self.second = [[[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil] autorelease]; } 永远不会被调用,所以我将 if 条件更改为 if(self.second==nil) 这有效,但我在对象分配中的图表仍在上升。
    • 这是我在(第一个)ViewController1 按钮操作方法中所做的 -(IBAction) loadSecond{ if(second==nil) self.second=[[[ViewController2 alloc]initWithNibName:@"ViewController2 " bundle:nil]autorelease]; [self.view addSubview:second.view]; }
    • @Rengers:retain)ViewController2* sceond 是什么意思?
    猜你喜欢
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2012-03-21
    相关资源
    最近更新 更多