Objective C 自动释放问题
嘿,我有一个关于自动释放的快速问题。我基本上了解它是如何工作的,但我想知道以下内容是否会造成内存泄漏。
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSString* string = [[[NSString alloc] init] autorelease];
[[string retain] autorelease];
[pool drain];
字符串会被发送两条释放消息吗?
Hey, I've got a quick autorelease question. I understand basically how it works, but I was wondering if the following would create a memory leak.
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSString* string = [[[NSString alloc] init] autorelease];
[[string retain] autorelease];
[pool drain];
Will the string be sent two release messages?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将您与对象的保留计数的交互纯粹视为增量。
如果将其增加 1,则需要将其减少 1 才能释放该对象。
所以 - 是的 - 您在该代码中将其增加一两次并减少一两次。结果将是两次发布。
Think of the your interaction with the retain count of an object purely as a delta.
If you increase it by one, you need to decrease it by one for that object to potentially be released.
So -- yes -- you increased it by one twice and decreased it by one twice in that code. Two releases on drain will be the result.
这不会造成内存泄漏,你是对的,它将从自动释放池中发送两条释放消息。只要每个分配/保留/复制都有一个释放/自动释放,就不应该出现任何泄漏。
That will not create a memory leak and you are correct, it will be sent two release messages from the auto release pool. As long as you have one release/autorelease for every alloc/retain/copy you should not be getting any leaks.