【问题标题】:Xcode memory leakXcode 内存泄漏
【发布时间】:2011-06-23 12:54:56
【问题描述】:

我在调用以下方法时出现内存泄漏

- (NSArray *) children
{
NSArray *children = [node objectForKey:TFHppleNodeChildrenKey];
NSMutableArray *hpple = [NSMutableArray arrayWithCapacity:[children count]];
for(NSDictionary *child in children) {
    [hpple addObject:[[TFHppleElement alloc] initWithNode:child]];
    [child release];
}
return hpple;
}

我在TFHppleElement 上遇到了内存泄漏,我分配了它,但我不确定在这种情况下释放它的最佳方法是什么? TFHppleElement initWithNode 看起来像这样:

- (id) initWithNode:(NSDictionary *) theNode
    {
 if (!(self = [super init]))
  return nil;

[theNode retain];
node = theNode;

return self;
 }

【问题讨论】:

  • [child release] 不应该在那里。将子元素添加到数组 children 的人不应该有额外的保留,一旦你修复了 TFHppleElement 泄漏,你就会崩溃。
  • 谢谢乔,你是对的,事情就是这样。我现在已经删除了。

标签: objective-c xcode memory-leaks


【解决方案1】:

您可以简单地自动释放该对象,让运行时负责释放它:

[hpple addObject:[[[TFHppleElement alloc] initWithNode:child] autorelease]];

【讨论】:

  • @user598241 再补充一点,您可以轻松地向TFHppleElement 添加一个elementWithNode: 便捷方法,该方法返回一个自动释放的对象。
【解决方案2】:

不放心,因为我不久前还没有开始使用 Objective-C,但是当你分配它时我会直接自动释放。这将使您不必管理发布并让运行时管理它的发布。

- (NSArray *) children
{
NSArray *children = [node objectForKey:TFHppleNodeChildrenKey];
NSMutableArray *hpple = [NSMutableArray arrayWithCapacity:[children count]];
for(NSDictionary *child in children) {
    [hpple addObject:[[[TFHppleElement alloc] initWithNode:child] autorelease]];
    [child release];
}
return hpple;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-02
    • 2016-04-02
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    相关资源
    最近更新 更多