【问题标题】:Correctly removing objects from view and array?从视图和数组中正确删除对象?
【发布时间】:2012-05-27 06:13:52
【问题描述】:

在我的“connect4”风格游戏中,我有一个表示 7x6 网格的数组,数组中的每个“单元格”都包含 NSNull 或 UIView 子类“CoinView”。以下是从 NSMutableArray 和主视图中删除对象的正确方法吗?

- (IBAction)debugOrigin:(id)sender {
    int x = 0;
    int y = 0;
    //get the coin object form the grid
    CoinView *coin = [[grid objectAtIndex:x] objectAtIndex:y];

    //cancel if there's no coin there
    if ([coin isKindOfClass:[NSNull class]]) { return; }

    //remove the coin from memory
    [coin removeFromSuperview];
    coin = nil;
    [[grid objectAtIndex:x] setObject:[NSNull null] atIndex:y]; //will this leak?

}

谢谢!

【问题讨论】:

  • 如果您使用的是 ARC,这应该没问题。使用 [array setObject:atIndex] 从数组中删除任何先前的对象,这会在幕后自动释放它。如果 CoinView 被保留在其他任何地方,它仍然会存在 - 但从本质上讲,它不是泄漏,因为某些东西仍然会引用它

标签: iphone arrays cocoa memory-management


【解决方案1】:

您的代码不会泄漏,而且实际上(几乎)是正确的。

您应该删除此注释,因为您没有处理代码中的内存(最终可能会让您对代码的实际作用感到困惑):

//remove the coin from memory

在以下行中,您将从其父视图中删除由局部变量“coin”引用的视图:

[coin removeFromSuperview];

然后您将 nil 分配给您的局部变量 coin,这是确保稍后在代码中不使用它的好习惯:

coin = nil;

据我所知,NSMutableArray 没有setObject:AtIndex:。请改用replaceObjectAtIndex:withObject:

[[grid objectAtIndex:x] replaceObjectAtIndex:y withObject:[NSNull null]]; //will this leak?

最后一点,我建议您阅读一下memory managementmemory leaks(来自Apple 的开发人员文档)。第一个为您提供了一些提示和技巧,使内存管理更容易理解。

【讨论】:

  • 在文本中放置代码时,用反引号 (`) 分隔,而不是星号。这样,它将是等宽的,更易于阅读,而不是斜体。
猜你喜欢
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 1970-01-01
  • 2013-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多