Objective C - 内存管理和自动释放???

发布于 2024-11-26 23:38:45 字数 55 浏览 0 评论 0原文

autorelease 是否保证在块结束时对象将被释放?

还是手动释放对象更好?

Does autorelease guaranty that at the end of blocks the object will get released?

Or is it better to manually release objects?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绮筵 2024-12-03 23:38:45

它保证它会在块执行后某个时间释放,而不一定是紧接着执行。由运行时来确定确切的时间。

这没什么大不了的,除非你正在做一些使用大量自动释放变量的事情,比如在一个大循环中创建它们,或者如果你正在创建大型自动释放对象,比如 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.

暮凉 2024-12-03 23:38:45

如果一个对象是自动释放的,那么你不能手动释放它(当然除非它是保留)。 NSAutoRelease 池是 UIKit 事件处理程序的一部分,将为您释放它。如果您要手动释放对象,池可能会导致崩溃或其他未定义的行为,因为对象将被双重释放

如果存在生成大量对象或在对象中使用大量内存的情况,您可以通过创建自己的 NSAutoReleasePool 来抢先自动释放它们(可能在循环中) code> - 池可以嵌套。

If an object is autoreleased, you MUST not manually release it (unless it is retained of course). The NSAutoRelease pool which is part of the UIKit event handler will release it for you. If you were to manually release the object, the pool may cause a crash or other undefined behavior as the object will be doubly-released.

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 own NSAutoReleasePool - pools can be nested.

任性一次 2024-12-03 23:38:45

最好是释放对象而不是自动释放,除非您有明确的理由使用自动释放,例如在返回方法保留的对象时使用自动释放,并且您无法避免它。

基本上应该使用自动释放作为完全避免内存管理的借口。您希望尽快释放对象。 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文