Cocoa memory management mainly relies on reference counting, and the NSAID utoreleasepool is used to support it. The objects stored in the autorelease pool will be release when it is drain.
We all know that when the release method of an object is triggered, the object will be destroyed and no reference can be made to it. Otherwise, an exception will occur. however, if the autorelease method is triggered when it is destroyed, the object enters the corresponding autorelease pool, its life is extended (only when pool drain is actually destroyed ).
In the reference counting environment, cocoa always expects that an autorelease pool exists in every thread. If it does not exist, the objects that are autoreleased will not be destroyed, resulting in memory leak. (in this case, xcode displays the warnning information on the console)
Like normal nsobject, the initialization of the nutoreleasepool is alloc + init, But the pool cannot be retain, because it will be destroyed by default during drain. another thing to note is that when the pool is destroyed, it is usually used instead of its release method, but drain! The reason is to makeProgramIt is also compatible with the reference counting memory management environment and garbge collection environment because drain triggers the collect garbage action in the garbage colloection environment.
In general, an autorelease pool already exists in the main thread of the application. In either case, the developer needs to create the autorelease pool by himself:
- In main thread, a large number of autoreleased objects appear in a method. To avoid increasing memory footprint, You can manually create some autorelease pools for Drain objects.
- Create a new thread and access cocoa. You need to create the autorelease pool before the access.
At last, a stack is maintained in each thread, where all pools created but not destroyed in this thread are placed. Every time a new pool is created, it is located at the top of the stack, and the corresponding autoreleased object will be placed in it. when pool drain is used, it will be removed from the top of the stack and release will remove the objects it contains.