簡體   English   中英

我應該將傳遞的vars / object排除在自動釋放池之外嗎?

[英]Should I leave passed vars/objects out of the autorelease pool?

我有一個線程可以在循環中修改傳遞給對象的指針(該對象已分配並保留在調用線程中)。 如果將指針放在自動釋放池中,有時會出錯,因為該對象在不應該釋放時被釋放。 我從自動釋放池中取出了它,這似乎可行。 但是,我擔心內存泄漏,因為如果我根本不使用自動釋放池,則會出現嚴重的泄漏。

-(void)my_thread:(NSArray*)parameters;
{       
    //keep this out of the autorelease pool
    Object *theObject;
    [[parameters objectAtIndex:2] getValue:&theObject];

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

    //do stuff to theObject

    [pool release];
}

鑒於這種:

-(void)my_thread:(NSArray*)parameters;
{       
...
}

當所述方法是線程的入口點時,使parameters有效的唯一方法是生成線程是否保留參數 保留和自動發布,而只是保留。

換句話說:自動釋放池永遠不會有助於線程安全。 自動釋放的對象永遠無法安全地遍歷線程邊界。 必須在發送線程中硬保留對象,而接收線程必須釋放該對象。 故事結局。

或按代碼:

-(void)my_thread:(NSArray*)parameters;
{     
    ... do your stuff here, including your autorelease pool dance
    [parameters release];  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM