在 Objective-C 中释放对象的正确方法是什么
我必须确认一件事。 我以这种方式释放我的对象。
[lblTotalQty, lblTotalAmt, imgEmptyBag, lblEmptyBagMsg release];
这不是一个正确的方法吗?
请指导我。
I have to confirm with something.
I am releasing my objects in this way.
[lblTotalQty, lblTotalAmt, imgEmptyBag, lblEmptyBagMsg release];
is this not a proper way?
Please guide me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
逗号运算符将丢弃除最后一个之外的所有表达式,因此您的语句实际上将变为
“所以您不应该按照问题中指示的方式释放对象”。单独执行它们,即分别对每个对象调用release。
Comma operators will discard all expressions except the last so your statement will in effect become
So you shouldn't release objects in the way you've indicated in the question. Do them individually i.e. call release on each object separately.
很难说出你在这里问的是什么,因为你没有提供任何背景信息。
一方面,我从未见过有人使用逗号分隔的标识符列表来发送一条消息,就像您在示例中所做的那样......但我认为这不是问题的重点。
除了使用自动释放池之外,向对象发送
release
消息是释放它们的唯一方式。释放对象的困惑通常更多的是“何时”而不是“如何”的问题。每个人都知道“如何”(调用
release
)。更大的问题通常是“我应该什么时候释放或保留一个对象”。Its really hard to tell what you're asking here because you give no context.
For one thing, I've never seen anyone use a comma separated list of identifiers to send a single message to, as you do in your example... but I suppose that's not the point of the question.
With the exception of using autorelease pools, sending the
release
message to an object is the only way of releasing them.The confusion with releasing object is usually more a question of "when" not "how". Everyone knows "how" (call
release
). The bigger question is usually "when should I be releasing or retaining an object".关于如何,您可以通过发送释放消息来释放对象:
以前从未见过逗号语法,有人建议只向最后一个对象发送消息(谁能确认这个?)
关于何时,这是一个很长的故事,我建议您阅读有关该主题的 Apple 文档;
你可以开始 这里。
基本上,您必须跟踪对象所有权,以避免两方两次释放同一个对象,或者相反,永远不会。
乍一听起来很麻烦,但在软件设计方面这是一个非常好的实践;这种所有权层次结构为您的代码带来了有意义的结构。
或者,如果您正在为 Mac 编码,则可以使用垃圾收集。此外,如果您正在为 iOS 5.0+ 编码并开始一个新项目,您可以利用新的 ARC(自动引用计数)功能,该功能基本上是由编译器自动生成的手动引用计数代码:两者的最佳选择世界。
Regarding the how, You release objects by sending the release message:
Never seen the comma-syntax before, and someone suggested only the last object is sent the message (Can anyone confirm this?)
Regarding the when, that's a long story and I recommend you read Apple's docs on the subject;
you could start here.
Basically, you must keep track of object ownership to avoid having two parties deallocate the same object twice, or conversely, never.
Sounds cumbersome at first, but it's a very good practice in terms of software design; This ownership hierarchy brings meaningful structure to your code.
Alternatively, IF you are coding for the Mac, you can use Garbage Collection. Also, if you are coding for iOS 5.0+ and are starting a new project, you can take advantage of the new ARC (Automatic Reference Counting) functionality, which is basically Manual Reference Counting code auto-generated by the compiler: The Best of Both Worlds.