Why is @autoreleasepool still needed with ARC?

2019-01-01 06:22发布

For the most part with ARC (Automatic Reference Counting), we don't need to think about memory management at all with Objective-C objects. It is not permitted to create NSAutoreleasePools anymore, however there is a new syntax:

@autoreleasepool {
    …
}

My question is, why would I ever need this when I'm not supposed to be manually releasing/autoreleasing ?


EDIT: To sum up what I got out of all the anwers and comments succinctly:

New Syntax:

@autoreleasepool { … } is new syntax for

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
…
[pool drain];

More importantly:

  • ARC uses autorelease as well as release.
  • It needs an auto release pool in place to do so.
  • ARC doesn't create the auto release pool for you. However:
    • The main thread of every Cocoa app already has an autorelease pool in it.
  • There are two occasions when you might want to make use of @autoreleasepool:
    1. When you are in a secondary thread and there is no auto release pool, you must make your own to prevent leaks, such as myRunLoop(…) { @autoreleasepool { … } return success; }.
    2. When you wish to create a more local pool, as @mattjgalloway has shown in his answer.

7条回答
何处买醉
2楼-- · 2019-01-01 07:05

Quoted from https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html:

Autorelease Pool Blocks and Threads

Each thread in a Cocoa application maintains its own stack of autorelease pool blocks. If you are writing a Foundation-only program or if you detach a thread, you need to create your own autorelease pool block.

If your application or thread is long-lived and potentially generates a lot of autoreleased objects, you should use autorelease pool blocks (like AppKit and UIKit do on the main thread); otherwise, autoreleased objects accumulate and your memory footprint grows. If your detached thread does not make Cocoa calls, you do not need to use an autorelease pool block.

Note: If you create secondary threads using the POSIX thread APIs instead of NSThread, you cannot use Cocoa unless Cocoa is in multithreading mode. Cocoa enters multithreading mode only after detaching its first NSThread object. To use Cocoa on secondary POSIX threads, your application must first detach at least one NSThread object, which can immediately exit. You can test whether Cocoa is in multithreading mode with the NSThread class method isMultiThreaded.

...

In Automatic Reference Counting, or ARC, the system uses the same reference counting system as MRR, but it insertsthe appropriate memory management method callsfor you at compile-time. You are strongly encouraged to use ARC for new projects. If you use ARC, there is typically no need to understand the underlying implementation described in this document, although it may in some situations be helpful. For more about ARC, see Transitioning to ARC Release Notes.

查看更多
登录 后发表回答