【问题标题】:Leaks from nowhere, what am I doing wrong?不知从何处泄漏,我做错了什么?
【发布时间】:2011-03-10 18:00:15
【问题描述】:

我在发布和泄漏方面遇到了真正的麻烦。我有一个不会停止泄漏的数组!这是我的代码: 我在 .h 中声明了 otherValuesArray 我尝试了数百种不同的方法,包括自动释放。

谁能告诉我我做错了什么?谢谢

otherValuesArray = [[NSMutableArray array] retain]; //89% leak

NSString *tempString;
tempString = [[NSString stringWithFormat:@"%d",challengeID] autorelease];
[otherValuesArray addObject:[NSString stringWithString:tempString]]; // 11% leak
tempString=nil;

tempString = [[NSString stringWithFormat:@"%d",scoreMultiQuant] autorelease];
[otherValuesArray addObject:[NSString stringWithString:tempString]];
tempString=nil;

int challengeDoneTemp = [challenges otherValues:otherValuesArray];

tempString=nil;
[tempString release];

otherValuesArray = nil;
[otherValuesArray release];

【问题讨论】:

  • 顺便说一句,我在其他 [otherValuesArray addObject:[NSString stringWithString:tempString]]; 行上遇到了泄漏,直到我添加了:tempString=nil;。我也尝试更改为otherValuesArray = [[NSMutableArray array] autorelease];otherValuesArray = [NSMutableArray array]; 但它崩溃了
  • Xcode 没有泄漏,它只是您用来编写代码的 IDE。

标签: objective-c cocoa-touch memory nsmutablearray memory-leaks


【解决方案1】:

交换最后两行。将otherValuesArray 设置为nil 后,发送释放消息就没有意义了。它已经为零,因此释放无效。因此,您正在泄漏该内存,因为它没有被释放。正确的代码将是,

[otherValuesArray 发布]; // 第一次发布 其他值数组 = 无; // 然后设置为零

还有stringWithFormat 已经自动发布。所以你不需要向它发送自动释放消息。由于容器 otherValuesArray 正在泄漏,因此您正在泄漏。

而且(尽管与泄漏无关)您根本不需要 tempString。您可以在一行中完成此操作:

[otherValuesArray addObject:[NSString stringWithFormat:@"%d",challengeID]];

【讨论】:

  • 哇,这很简单!那是一种享受,谢谢。我也摆脱了 tempString,并完成了上面的最后一个提示。
【解决方案2】:

正如 taskinoor 所指出的,存在许多内存管理问题。

这是程序的简化形式:

NSMutableArray * tmp = [NSMutableArray new];
[tmp addObject:[NSString stringWithFormat:@"%d",challengeID]];
[tmp addObject:[NSString stringWithFormat:@"%d",scoreMultiQuant]];
assert(challenges);
int challengeDoneTemp = [challenges otherValues:tmp];
self.otherValuesArray = tmp;
[tmp release], tmp = 0;

【讨论】:

  • 只是一个补充。属性 otherValuesArray 应该保留在这里,并且必须在 dealloc 中释放。
  • @taskinoor +1 是的。更好,如果 otherValuesArray 是不可变的:@property (copy) NSArray * otherValuesArray;
  • 谢谢,我试试看。使用临时数组而不是仅仅写入 otherValuesArray 有什么好处? self.otherValuesArray = tmp; 是否会覆盖 self.otherValuesArray 中已有的数据?不可变的好处是什么? @taskinoor 另外,如果你不介意解释,这个类可以有一个 dealloc,因为它是一个链接到 UIViewController 的 NSObject?
  • @Scott Walker a) 你应该设计并发执行 b) 使用访问器/属性是设置它的方法,因为它包含设置数组的实现(不要重复自己,或引入错误——setter 的实现应该处理内存管理,有时还有其他细节)c)是的,使用属性/访问器/setter 应该替换 ivar 指向的内容,因此在某种意义上“数据被覆盖”。 self.otherValuesArray = thing 等于 [self setOtherValuesArray:thing]。不可变的好处是易于维护,(续)
  • (cont) 更好地实现并发性,并且(作为低级实现细节)可以减少分配计数/内存使用量。
猜你喜欢
  • 2015-11-08
  • 1970-01-01
  • 1970-01-01
  • 2013-03-16
  • 1970-01-01
  • 2014-02-16
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多