iOS開發(fā)中@autoreleasepool使用說明

Document

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html

About Autorelease Pool Blocks

  1. 代碼塊

    @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的消息。

  2. 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

  1. 寫基于命令行的的程序時,就是沒有UI框架,如AppKit等Cocoa框架時。(使用的較少)

  2. 寫循環(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)存

  3. 創(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;
        }
    }
    

參考文檔

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容