Objective-C 内存管理奇怪的结果
我使用循环重复调用函数,并且循环在线程内运行。该线程有一个自动释放池。
我在该函数中有以下代码:
NSXMLDocument* undoXML;
NSData* undoData = [NSData dataWithContentsOfFile:undoFilePath];
undoXML = [[NSXMLDocument alloc] initWithData:undoData 选项:NSXMLDocumentTidyXML 错误:&err];NSData* undoData2;
undoData2 = [undoXML XMLData];[undoData2 发布];
[undoXML 发布];
我得到以下奇怪的结果:
- 每次循环调用此函数时,我的程序都会泄漏内存。
- 当我将以下代码添加到函数中时:
NSData* undoData3;
undoData3 = [undoXML XMLData];
[undoData3释放];
我的程序泄漏的内存比以前更多。
我真的很困惑,我非常需要帮助弄清楚发生了什么事。也许我的自动释放池无法正常工作?为什么会发生这种情况?
I am calling a function repeatedly with a loop, and the loop runs inside of a thread. The thread has an autorelease pool.
I have the following code inside that function:
NSXMLDocument* undoXML;
NSData* undoData = [NSData dataWithContentsOfFile:undoFilePath];
undoXML = [[NSXMLDocument alloc] initWithData:undoData options:NSXMLDocumentTidyXML error:&err];NSData* undoData2;
undoData2 = [undoXML XMLData];[undoData2 release];
[undoXML release];
I'm getting the following strange results:
- My program is leaking memory every time this function is called by the loop.
- When I add the following code to the function:
NSData* undoData3;
undoData3 = [undoXML XMLData];
[undoData3 release];
My program leaks even more memory than before.
I'm really confused and I badly need help figuring out what's going on. Maybe my autorelease pool isn't working correctly? Why is this happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(4)
undoData
应预设为自动释放(根据命名约定 dataWithContentsOfFile:
返回一个自动释放对象)。但除非您有自己的自动释放池,否则在活动池耗尽之前(即函数返回后的某个时间),设置为自动释放的任何内容都不会真正被释放。
您的线程可能有自己的自动释放池,但除非您在自己的函数内创建自动释放池,否则在函数退出之前不会释放任何内容。
如果您想在函数中间触发自动释放对象的耗尽(例如每个循环一次),您需要管理自己的自动释放池。
while(looping) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// do stuff that produces autoreleased objects
[pool drain];
}
另外,根据 cobbal 对您问题的评论,看来您不应该发布 undoData2
(或undoData3
)。根据命名约定 -[NSXMLDocument XMLData]
应该返回一个自动释放的对象。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
你确定它漏水了吗?或者只是尺寸变大了?
您的循环是什么样的?自动释放池是如何集成到其中的?
自动释放池必须位于循环内部,否则循环将随着时间的推移积累大量内存。泄漏工具没有显示泄漏表明您违反了内存管理规则或者您的循环不正确。
Are you sure it is leaking? Or is it simply growing in size?
What does your loop look like and how is the autorelease pool integrated into it?
The autorelease pool must be inside the loop or your loop will just build up tons of memory over time. That the leaks instrument doesn't show leaks indicates that you have violated the memory management rules or your loop is incorrect.