@autorelease 和循环

发布于 2024-12-24 19:48:52 字数 307 浏览 6 评论 0原文

假设我有这样的代码:

@autoreleasepool {
  for(int i = 0; i < relatedSlideDecks.count; i++) {
    MyClass *myObject = [MyClass new];
    ... something happens here
    [myObject release];
  {
}

我还需要 [myObject release]; 吗?或者会因为@autoreleasepool而自动释放?

Assume I have a code like this:

@autoreleasepool {
  for(int i = 0; i < relatedSlideDecks.count; i++) {
    MyClass *myObject = [MyClass new];
    ... something happens here
    [myObject release];
  {
}

do I still need that [myObject release];? Or will it be autoreleased because of @autoreleasepool?

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

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

发布评论

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

评论(3

给妤﹃绝世温柔 2024-12-31 19:48:53

仍然需要释放 myObject,因为 @autoreleasepool 块不会更改 内存管理规则,其中规定您必须放弃您拥有的对象的所有权,并且您拥有 myObject。您不能做的一件事是使用在该块之外的 @autoreleasepool 块内自动释放的对象。如果程序的一小部分可能创建大量需要尽快释放的自动释放对象,而不是等到主自动释放池耗尽时,它会很有用。

It is still a requirement to release myObject because the @autoreleasepool block does not change the memory management rules, which state that you must relinquish ownership of objects you own, and you own myObject. The one thing you can't do is use an object that was autoreleased within an @autoreleasepool block outside of that block. It is useful if you have a small section of your program that may create a lot of autoreleased objects that need to be released as soon as possible rather than until the main autorelease pool is drained.

撩动你心 2024-12-31 19:48:52

如果您使用 ARC,则根本没有必要。

否则您需要调用该释放方法。

确保 @autoreleasepool 块的唯一事情是,一旦您的代码执行通过它,任何具有 autorelease 调用的对象都将获得它的release 调用。

If you're using ARC it shouldn't be necessary at all.

Otherwise you need to call that release method.

The only thing that ensures that @autoreleasepool block is that once your code executes past it, any object with an autorelease call, will get it's release call.

一个人的旅程 2024-12-31 19:48:52

是的,您仍然需要 [myObject release]@autoreleasepool 的存在不会导致对象神奇地自动释放。它只会导致自动释放的对象在自动释放池耗尽时被清理。您可以在高级内存管理编程指南中了解更多信息。

Yes, you still need that [myObject release]. The presence of @autoreleasepool doesn't cause objects to magically get autoreleased. It just causes objects that are autoreleased to be cleaned up when the autorelease pool drains. You can read more at the Advanced Memory Management Programming Guide.

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