【问题标题】:Released object crashes App -- problem with alloc/init memory management释放的对象崩溃应用程序 - 分配/初始化内存管理问题
【发布时间】:2010-09-14 18:16:42
【问题描述】:

我有一个我分配和启动的翻转视图类。但是,当我释放它时,应用程序崩溃了。如果我不发布它,该应用程序可以正常工作,看起来如此。我发布它时收到的错误消息是:

Malloc - 对象错误:被释放的对象指针未被分配。

如果您能帮助我,我将不胜感激。

- (IBAction)showInfo {
    FlippedProduceView *flippedView = [[FlippedProduceView alloc]initWithIndexPath:index];

    flippedView.flipDelegate = self;

    flippedView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;

    [self presentModalViewController:flippedView animated:YES];

    //[flippedView release]; //******** Maybe A Memory Leak *********\\
}

【问题讨论】:

    标签: iphone memory-leaks memory-management malloc


    【解决方案1】:

    将最后一行放在那里是正确的,因为当您将“flippedView”作为“presentModalViewController”的参数传递时,它会在内部保留“flippedView”(无需编写任何额外的代码)。

    Apple 框架中的大多数函数都会保留一个对象,如果它们在逻辑上看起来应该如此。如果您正在呈现一个视图控制器,那么您实际上不会想要传递一个已释放(或即将被释放)的控制器来呈现。您在其中呈现的包含视图控制器将保留子控制器,直到它被解除。

    所以我们很清楚,这里是正确的代码(假设没有其他异常情况):

    - (IBAction)showInfo {
    
    // Here the retain count gets incremented to 1 (usually "alloc" or "copy" does that)
    FlippedProduceView *flippedView = [[FlippedProduceView alloc]initWithIndexPath:index];
    
    // Retain count is unchanged
    flippedView.flipDelegate = self;
    
    // Retain count is unchanged
    flippedView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    
    // Retain count is incremented again inside this method (to 2)
    [self presentModalViewController:flippedView animated:YES];
    
    // Retain count is decremented by 1 (back to 1)
    [flippedView release]
    }
    
    // ... Other code
    
    // Finally, whenever the view controller gets dismissed, it will be released again
    // and the retain count will be 0, theoretically qualifying it for deallocation
    

    【讨论】:

      【解决方案2】:

      您的presentModalViewController: 消息应在flippedView 上致电retain。这将防止它被释放,直到presentModalViewController: 的目的完成。然后,您可以在此例程结束时调用[flippedView release]。除非还缺什么?

      【讨论】:

      • 感谢 fbrereto 回答我的问题。我是一个完整的新手,正在开发我的第一个应用程序。我快完成了,但这个问题让我退缩了。我不明白我将如何编码您提到的表达式。会是这样吗?:FlippedProduceView *fView = [[FlippedProduceView alloc]initWithIndexPath:index]; [f查看保留]; fView.flipDelegate = self; fView.modalTransitionStyle = UIModalTransitionStyleFlipHorizo​​ntal; [self presentModalViewController:fView Animation:YES]; NSLog(@"保留计数 fView:%d",[fView retainCount]); [f查看发布];
      • 好的,会是这样吗? [self presentModalViewController:[fView retain] animated:YES];
      • presentModalViewController 内部,您可以在收到的视图上调用retain。您不需要在 showInfo 中调用 retain,因为 alloc/init 阶段会自动为您执行此操作。然后,您可以从showInfo 中调用release,并且该对象将仍然存在,因为它被presentModalViewController 保留。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多