Objective C - 内存管理和自动释放???
autorelease 是否保证在块结束时对象将被释放?
还是手动释放对象更好?
Does autorelease guaranty that at the end of blocks the object will get released?
Or is it better to manually release objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它保证它会在块执行后某个时间释放,而不一定是紧接着执行。由运行时来确定确切的时间。
这没什么大不了的,除非你正在做一些使用大量自动释放变量的事情,比如在一个大循环中创建它们,或者如果你正在创建大型自动释放对象,比如 UIImages。在这些情况下,您应该在完成后手动释放,否则自动释放是完全可以接受的。
It guarantees it will be released sometime after the block executes, not necessarily immediately after. It's up to the runtime to determine exactly when.
It's not big deal unless you're doing something with a lot of autoreleased variables, like creating them in a big loop, or if you're creating large autoreleased objects, like UIImages. In these cases, you should manually release when you're through, otherwise autorelease is perfectly acceptable.
如果一个对象是
自动释放
的,那么你不能手动释放
它(当然除非它是保留
)。 NSAutoRelease 池是 UIKit 事件处理程序的一部分,将为您释放
它。如果您要手动释放
对象,池可能会导致崩溃或其他未定义的行为,因为对象将被双重释放
。如果存在生成大量对象或在对象中使用大量内存的情况,您可以通过创建自己的 NSAutoReleasePool 来抢先自动释放它们(可能在循环中) code> - 池可以嵌套。
If an object is
autorelease
d, you MUST not manuallyrelease
it (unless it isretain
ed of course). The NSAutoRelease pool which is part of the UIKit event handler willrelease
it for you. If you were to manuallyrelease
the object, the pool may cause a crash or other undefined behavior as the object will be doubly-release
d.If there are cases where you generate a lot of objects or use a lot of memory in objects, you can pre-emptively
autorelease
them (perhaps in your loop) by creating your ownNSAutoReleasePool
- pools can be nested.最好是释放对象而不是自动释放,除非您有明确的理由使用自动释放,例如在返回方法保留的对象时使用自动释放,并且您无法避免它。
基本上应该使用自动释放作为完全避免内存管理的借口。您希望尽快释放对象。 Autorelease 只是表示该对象将在将来的某个时间被释放。
It's better to release objects rather than autorelease, unless of course you have an explicit reason to use autorelease, for example use autorelease when returning an object the method retained and you can't avoid it.
Basically autorelease should be used as an excuse to completely avoid memory management. You want to release objects as soon as you possible can. Autorelease just says the object will be released some time in the future.