Objective-c 中 release 和 dealloc 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/559295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:08:54  来源:igfitidea点击:

Difference between release and dealloc in objective-c

objective-cmemory

提问by hhafez

When deallocing a refrence I've seen releaseand deallocbeing used for example

例如,当我看到releasedealloc使用了一个引用时

-(void)dealloc
{
  [foo release];
  [nar dealloc];

  [super dealloc];
}

My question is when is releaseto be used and when is deallocto be used?

我的问题是什么时候release用,什么时候dealloc用?

Thanks

谢谢

回答by Chuck

Never call deallocexcept as [super dealloc]at the end of your class's deallocmethod. The releasemethod relinquishes ownership of an object. When a Cocoa object no longer has any owners, it may be deallocated — in which case it will automatically be sent a deallocmessage.

永远不要调用,dealloc除非[super dealloc]在类的dealloc方法结束时。该release方法放弃对象的所有权。当 Cocoa 对象不再有任何所有者时,它可能会被释放——在这种情况下,它会自动发送一条dealloc消息。

If you're going to program Cocoa, you need to read the Memory Management Guidelines. It's incredibly simple once you get over the initial hump, and if you don't understand what's in that document, you'll have lots of subtle bugs.

如果您要对 Cocoa 进行编程,则需要阅读内存管理指南。一旦你克服了最初的障碍,它就非常简单,如果你不理解该文档中的内容,你就会有很多微妙的错误。

回答by Abizern

The deallocstatement in your example is called when the object's retain count becomes zero (through an object sending it a release message).

dealloc当对象的保留计数变为零(通过对象向其发送释放消息)时,将调用示例中的语句。

As it is no longer needed, it cleans itself up by sending a releasemessage to the objects that it is holding on to.

由于不再需要它,它通过向release它持有的对象发送消息来清理自己。

回答by Vadoff

You're never supposed to call dealloc explicitly (unless it's [super dealloc] within the dealloc method, but that's the only exception). Objective-C handles memory management via reference counting, so you're simply supposed to match your allocs/retains with releases/autoreleases and let the object deconstruct itself.

您永远不应该显式调用 dealloc (除非它是 dealloc 方法中的 [super dealloc] ,但这是唯一的例外)。Objective-C 通过引用计数处理内存管理,因此您只需将分配/保留与发布/自动释放相匹配,并让对象自行解构。