Document
About Autorelease Pool Blocks
-
代碼塊
@autoreleasepool { // Code that creates autoreleased objects. }At the end of the autorelease pool block, objects that received an autorelease message within the block are sent a release message—an object receives a release message for each time it was sent an autorelease message within the block.
在的autoreleasepool代碼塊執(zhí)行結(jié)束的時候,自動釋放池收到一條autorelease消息,池中的對象收到一條release的消息。
-
autorelease的嵌套使用
@autoreleasepool { // . . . @autoreleasepool { // . . . } . . . }
Using Autorelease Pool Blocks
There are, however, three occasions when you might use your own autorelease pool blocks:
If you are writing a program that is not based on a UI framework, such as a command-line tool.
-
If you write a loop that creates many temporary objects.
You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.
If you spawn a secondary thread.
You must create your own autorelease pool block as soon as the thread begins executing; otherwise, your application will leak objects
什么時候使用@autpreleasepool
寫基于命令行的的程序時,就是沒有UI框架,如AppKit等Cocoa框架時。(使用的較少)
-
寫循環(huán),循環(huán)里面包含了大量臨時創(chuàng)建的對象。(使用AudioQueue播放音頻讀取頻繁數(shù)據(jù)的例子)
static void IJKSDLAudioQueueOuptutCallback(void * inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) { @autoreleasepool { IJKSDLAudioQueueController* aqController = (__bridge IJKSDLAudioQueueController *) inUserData; if (!aqController) { // do nothing; } else if (aqController->_isPaused || aqController->_isStopped) { memset(inBuffer->mAudioData, aqController.spec.silence, inBuffer->mAudioDataByteSize); } else { (*aqController.spec.callback)(aqController.spec.userdata, inBuffer->mAudioData, inBuffer->mAudioDataByteSize); } AudioQueueEnqueueBuffer(inAQ, inBuffer, 0, NULL); } }寫在@autpreleasepool 代碼塊中,讓每次執(zhí)行完成后可以及時的釋放臨時對象的內(nèi)存
-
創(chuàng)建了新的線程。(非Cocoa程序創(chuàng)建線程時才需要)
static void *SDL_RunThread(void *data) { @autoreleasepool { SDL_Thread *thread = data; pthread_setname_np(thread->name); thread->retval = thread->func(thread->data); return NULL; } }