【问题标题】:iPhone objective-c autoreleasing leakingiPhone Objective-C 自动释放泄露
【发布时间】:2010-03-31 16:54:14
【问题描述】:

我这样做:

NSString *fullpath = [[NSBundle mainBundle] pathForResource:@"text_file" ofType:@"txt"];

为什么会出现以下消息? 我的代码泄露了吗?

2010-03-31 13:44:18.649 MJIPhone[2175:207] *** _NSAutoreleaseNoPool(): Object 0x3909ba0 of class NSPathStore2 autoreleased with no pool in place - just leaking
Stack: (0x1656bf 0xc80d0 0xcf2ad 0xcee0e 0xd3327 0x2482 0x2426)
2010-03-31 13:44:18.653 MJIPhone[2175:207] *** _NSAutoreleaseNoPool(): Object 0x390b0b0 of class NSPathStore2 autoreleased with no pool in place - just leaking
Stack: (0x1656bf 0xc80d0 0xc7159 0xd0c6f 0xd3421 0x2482 0x2426)
2010-03-31 13:44:18.672 MJIPhone[2175:207] *** _NSAutoreleaseNoPool(): Object 0x390d140 of class NSCFString autoreleased with no pool in place - just leaking
Stack: (0x1656bf 0xc6e62 0xcec1b 0xd4386 0x24ac 0x2426)

【问题讨论】:

  • 表示在执行代码时您没有运行自动释放池;此行是否在您未设置内存管理的线程中?
  • 我刚刚在 main 函数中添加了该代码。

标签: iphone objective-c memory-management memory-leaks


【解决方案1】:

发生这种情况是因为您在线程中运行。用户线程不共享主线程自动释放池,因此您需要创建自己的。否则,像这样的对象永远不会被释放,从而泄漏。

在你的线程方法的开始,在循环之前,做:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

在返回之前,释放它:

[pool drain];

【讨论】:

  • 不应该是[pool drain]吗?
  • 嗯,看起来它们在非 GC 系统上是同义词。
  • @Frank 有趣。我一直认为release 更惯用,因为其他任何东西都暗示在通话后池会保持活动状态。此外,drain 读起来像是一个糟糕的双关语。但正如您所说,它们是同义词,文档实际上指出“您通常应该使用 drain 而不是 release。”。
【解决方案2】:

在您运行该行代码时,当前线程上尚未创建 NSAutoreleasePool

如果您在主线程上运行,Cocoa(和 Cocoa Touch)会自动为您提供一个自动释放池。如果您已安排在单独的线程上发生某些事情(其中还包括由performSelectorInBackground:withObject: 安排的事情),那么您需要提供自己的自动释放池。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多