2012-10-01 15 views
-1

我得到這兩種方法的內存泄漏警告。第二個叫第一個,顯然是泄漏的內存。有任何想法嗎?調用subtreebordercolor時潛在的對象泄漏

static UIColor *subtreeBorderColor(void) 
{ 
    return [UIColor colorWithRed:0.0f green:0.5f blue:0.0f alpha:1.0f]; 
} 


- (void) updateSubtreeBorder 
{ 
    CALayer *layer = [self layer]; 
    if (layer) { 


     // If the enclosing TreeGraph has its "showsSubtreeFrames" debug feature enabled, 
     // configure the backing layer to draw its border programmatically. This is much more efficient 
     // than allocating a backing store for each SubtreeView's backing layer, only to stroke a simple 
     // rectangle into that backing store. 

     PSBaseTreeGraphView *treeGraph = [self enclosingTreeGraph]; 
     if ([treeGraph showsSubtreeFrames]) { 
      [layer setBorderWidth:subtreeBorderWidth()]; 
      [layer setBorderColor:[subtreeBorderColor() CGColor]]; 

     } else { 
      [layer setBorderWidth:0.0]; 
     } 


    } 
} 

//3: Potential leak of an object 
//6: Calling 'subtreeBorderColor' 
//1: Entered call from 'updateSubtreeBorder' 
//13: Method returns an Objective-C object with a +0 retain count 
//12: Reference count incremented. The object now has a +1 retain count 
//6: Returning from 'subtreeBorderColor' 
//13: Object leaked: allocated object is not referenced later in this execution path and has a retain count of +1 

更新2:我只是完全改變了代碼和刪除臨時文件和清潔解決方案,這是我看到的 - 它發現錯誤,其中甚至沒有代碼

enter image description here

回答

2

簡單。你不需要在函數中調用- retain。這是完全是什麼autorelease模式是發明。由於您不使用alloc-init創建UIColor對象,因此您不會擁有它。沒有必要進一步使存儲器管理變得過於複雜。 :)

編輯:(爲了防止未來downvotes)現在,您編輯您的問題和代碼,以便它不再錯誤地返回保留的對象,以前的語句不再有效。是的,Xcode顯示了關於內存泄漏的通知,其中「甚至沒有代碼」,這很奇怪。是的,也許是一個編譯器錯誤。儘管如此,臨時(在我看來,完全有效的)解決方法是簡單地使用定義而不是函數。讓我們看看Xcode中說的話,如果你寫這個:

#define SUBTREE_BORDER_COLOR [UIColor colorWithRed:0.0f green:0.5f blue:0.0f alpha:1.0f] 
+0

試過,我仍然得到相同的內存泄漏警告 – TheLearner

+0

@TheLearner然後你在其他地方泄漏內存。這是您發佈的代碼**中的**問題。* – 2012-10-01 14:26:30

+0

沒有其他內存泄漏警告。在刪除第一個方法中的保留之後,請參閱警告列表的更新 – TheLearner

0

如果您希望按自己的方式使用「保留」,則還需要「釋放」從「subtreeBorderColor」方法返回的「UIColor」對象。

這是我的代碼,我不會在該自動釋放對象上執行「retain」。或者比這更好,只需使用ARC啓用我的代碼即可。

-1

兩個透水的答案是正確的

但是,如果因爲任何原因,你需要保留的目的是通過你的方法被退回,請遵守規則,重命名你的方法以「new」開頭(或者alloc或者retain或者copy),這樣每個人(和你也一樣)都會知道返回的對象是被保留的,所以調用的代碼知道它有責任在需要時釋放它。

+1

這個答案爲什麼會得到一個downvote?這在技術上並不正確。 Downvoter,任何推理? – 2012-10-01 15:04:56

+0

我在這裏獲得幫助,以解決我的問題,不要辯論誰的答案是否正確。這兩個答案都沒有解決我的問題 – TheLearner

+0

@ H2CO3讓我重申。我不是在辯論你的答案是否正確。 – TheLearner