2011-03-26 41 views
1

我只是在跟蹤儀器的一些內存泄漏的過程。它聲稱我在drawRect方法的中間泄漏。這裏是代碼:儀器聲稱內存泄漏與[UIColor CGColor]

- (void)drawRect:(CGRect)rect { 
    if (highColor && lowColor) { 
     // Set the colors for the gradient to the two colors specified for high and low 

     // The next line is allegedly leaking 
     [gradientLayer setColors:[NSArray arrayWithObjects:(id)[highColor CGColor], (id)[lowColor CGColor], nil]]; 
     gradientLayer.startPoint = CGPointMake(0.5, 0.2); 
    } 

    [super drawRect:rect]; 
} 

我在iPad上,所以我必須自己管理內存(也就是沒有垃圾回收)。任何人都可以看到這裏有什麼問題?我的理解是我不必釋放陣列,也不必釋放CGColors。另外,在樂器中有沒有什麼方法可以找出哪種物體泄漏,即。它是指NSArray還是CGColors?

任何幫助將不勝感激。謝謝。 PS:我從幾個月前的某個地方得到了GradientView的代碼;它工作得很好(除了揭露前面提到的內存泄漏)。你可以找到代碼here

編輯:

我也做了些研究和重構我的代碼如下:

- (void)drawRect:(CGRect)rect { 
    if (highColor && lowColor) { 
     // The following two lines are leaking 
     CGColorRef highCGColor = [highColor CGColor]; 
     CGColorRef lowCGColor = [lowColor CGColor]; 

     // Set the colors for the gradient to the two colors specified for high and low 
     [gradientLayer setColors:[NSArray arrayWithObjects:(id)highCGColor, (id)lowCGColor, nil]]; 
     gradientLayer.startPoint = CGPointMake(0.5, 0.2); 

     CGColorRelease(highCGColor); 
     CGColorRelease(lowCGColor); 
    } 

    [super drawRect:rect]; 
} 

不過,我想不通爲什麼兩個CGColors仍在泄漏。我在方法結束時釋放它們。 NSArray在釋放時是否可以正確釋放它們?仍然困惑...

回答

0

我不是專家在iphone/ipad上的內存管理,但我會這樣做的方式: 嘗試與NSAutoreleasepool在你的如果,池然後處理內存管理,所以你必須:

if... 
NSAutoreleasePool *mypool=[[NSAutoreleasePool alloc]init]; 
... 
[mypool drain]; 

試一下,看看是否仍然有泄漏,但切記不要刪除你釋放顏色的2行。

+0

事實證明,我實際上必須刪除我釋放我的顏色的兩行。他們錯了,因爲我根據CoreFoundation內存管理規則不擁有這兩種顏色。 – McKrassy 2011-05-06 07:50:54

0

在UIView中如何聲明highColor和lowColor?他們是否被適當釋放/自動釋放?你的gradientLayer對象的聲明怎麼樣,是否被正確釋放?下面是我在一個階段用於在UIView上創建漸變的一些代碼。它不是使用圖層,而是直接繪製到當前上下文中。也許它可能有所幫助:

- (void)drawRect:(CGRect)rect { 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGGradientRef myGradient; 
    CGColorSpaceRef myColorSpace; 
    size_t num_locations = 3; 
    CGFloat locations[3] = {0.0, 0.5, 1.0}; 
    CGFloat components[12] = {0.855, 0.749, 0.196, 1.0, 
           0.973, 0.933, 0.267, 1.0, 
           0.855, 0.749, 0.196, 1.0}; 
    myColorSpace = CGColorSpaceCreateDeviceRGB(); 
    myGradient = CGGradientCreateWithColorComponents(myColorSpace, components, locations, num_locations); 

    CGPoint myStartPoint, myEndPoint; 
    myEndPoint.x = self.bounds.size.width; 

    CGContextDrawLinearGradient(context, myGradient, myStartPoint, myEndPoint, 0); 

    CGColorSpaceRelease(myColorSpace); 
    CGGradientRelease(myGradient); 
} 
0

您不應該釋放highCGColor和lowCGColor。