簡體   English   中英

我該如何解決此內存泄漏? NSInvocation

[英]How can I solve this memory Leak? NSInvocation

-(void)invokeMethod
{
    NSMethodSignature * sig = [[source class] instanceMethodSignatureForSelector:@selector(mySelector:)];
    NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:sig];

    [invocation setTarget:myTarget];
    [invocation setSelector:@selector(mySelector:)];

    MySubClassOfNSInvocationOperation * command = [[[MySubClassOfNSInvocationOperation alloc] initWithInvocation:invocation] autorelease];

    //setArgument retains command
    [invocation setArgument:&command atIndex:2];

    //addOperation retains command until the selector is finished executing
    [operationQueue addOperation:command];
}


-(void)mySelector:(MySubClassOfNSInvocation*)command
{
    //Do stuff
}

我不知道到底發生了什么,但是NSInvocationMySubClassOfNSInvocationOperation正在泄漏

當我刪除行時:

[invocation setArgument:&command atIndex:2];

它不會泄漏,因此將命令作為參數傳遞時會出現某種問題。

您可能有一個引用計數循環...一種情況,其中command保留invocationinvocation保留command並且都不希望在自己的dealloc方法之前釋放-導致它們從未被釋放。

您需要確定兩個對象中哪個哪個對象在層次結構上優先於另一個對象,並確保該下級對象不保留另一個對象。 順便說一句- NSInvocation ,除非你調用不會保留參數retainArguments 或者,您可以實現close方法,手動告訴一個釋放另一個,從而中斷循環。

在我自己的一個項目中發現NSInvocation確切問題后,我寫了“ 避免保留周期的規則 ”一文。

似乎setArgument方法保留了緩沖區(在這種情況下-您的命令對象)。 設置后可以嘗試釋放命令。 但您應該小心)。 當我的朋友的應用程序無法在新的iPhone操作系統上運行時,我的朋友感到困惑,因為他通過添加一行附加附加的發布消息來糾正了蘋果的漏洞。 當蘋果在新操作系統中進行更正時,此行是導致應用崩潰的原因)

這行上的多余的&符號是什么:

[invocation setArgument:&command atIndex:2];

您正在傳遞命令的指針。 對我來說這似乎是錯誤的。

暫無
暫無

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

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