如何知道一个对象是否自动释放?
我对某些对象在我不知情的情况下自动释放感到有点恼火。他们是这样可能是一件好事,但如果是的话,我想知道。文档没有说明哪些方法 autorelease 对象,所以我通常测试我的前进方式,在我看来这是愚蠢的。例如,[NSDate date] 自动释放对象,[NSArray arrayWithObjects:...] 也是如此。如果没有文档告诉你,你怎么知道?
我开始看到一种模式,尽管像这样的方法(使用静态函数创建对象的方法)总是返回自动释放的对象。这总是正确的吗?
I'm getting a a bit annoyed about some objects being autoreleased without me knowing. It's probably a good thing that they are, but if they are, I want to know. The documentation doesn't say which methods autorelease objects, so I usually test my way forward, which in my opinion is silly. For example, [NSDate date] autoreleases the object, and so does [NSArray arrayWithObjects:...]. How do you know without the documentation telling you?
I'm starting to see a pattern though that methods like these, the ones that create objects with a static function, always returns the autoreleased object. Is this always true?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,如果您
init
、copy
或retain
一个对象,您就有责任释放它。如果您不这样做,您不负责发布它。https://developer.apple.com/库/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html
Basically, if you
init
,copy
, orretain
an object you are responsible for releasing it. If you don't, you are not responsible for releasing it.https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html
方法签名本身告诉你。具有“classNameWithData:data1:data2”等签名的方法的模式是返回该事物的 alloc/init/autorelease 实例。它们在那里很方便,因此您不必这样做。
如果您不想要某些东西的自动释放版本,那么不要以这种方式实例化它们,并使用正确的分配/初始化,并在完成后释放。这种方法更加明确,并且更容易出错,因为如果抛出异常,您的发布块可能会被错过,但这就是您为此付出的代价。
The method signature itself tells you. The pattern to methods with signatures like "classNameWithData:data1:data2" is to return an alloc/init/autorelease instance of that thing. They are conveniences there so that you don't have to do it.
If you do not want an autorelease version of something, then do not instantiate them that way, and use the proper alloc/init, and release when you are done. This method is much more explicit, and a bit more error prone because if an exception is thrown your release block could get missed, but that is the price you pay for having it that way.