2013-03-15 46 views
0

在我的UIView中,我有幾個CGPath存儲在一個NSArray(availablePaths)中。爲什麼在釋放先前創建的CGMutablePathRef時會得到SIGABRT?

之前繪製任何東西,我創建一個縮放版本的每個CGPath 並替換數組中的舊的。

我使用下面的代碼在drawRect中獲得一個SIGABRT。

- (void) scaleAllPaths: (CGFloat) scaleFactor 
{ 

CGAffineTransform transform = CGAffineTransformMakeScale(scaleFactor, scaleFactor); 
CFIndex i; 
for(i=0;i<[availablePaths count];i++){ 
    id obj = [availablePaths objectAtIndex:i]; 
    CGPathRef oldPath = (CGPathRef)obj; 
    CGMutablePathRef newPath = CGPathCreateMutable(); 
    CGPathAddPath(newPath, &transform, oldPath); 
    [availablePaths replaceObjectAtIndex:i withObject:(id) newPath]; 
    CGPathRelease(newPath); // <--- causes SIGABRT in drawRect: 
} 
} 
-(void)drawRect:(CGRect)rect 
{ 
... 
for (int i = 0; i < currentPathIndex; i++) { 
     id obj = [availablePaths objectAtIndex:i]; 
     CGPathRef path = (CGPathRef)obj; 
     CGContextBeginPath(context); 
     CGContextAddPath(context, path); // <--- SIGABRT 
     CGContextDrawPath(context, kCGPathEOFill); 

} 
... 

沒有CGPathRelease(NEWPATH)繪製工作正常, 但當然,我得到了內存泄漏。

回答

1

嘗試找到的解決方案here添加CGPathRef s到NSMutableArray:包裝CGPathRef裏面UIBezierPath

編輯:看起來你可以使用-[UIBezierPath applyTransform:]來避免CGPathRefscaleAllPaths:

- (void) scaleAllPaths: (CGFloat) scaleFactor 
{ 
    CGAffineTransform transform = CGAffineTransformMakeScale(scaleFactor,scaleFactor); 
    for (UIBezierPath *bezierPath in availablePaths){ 
    [bezierPath applyTransform:transform]; 
    } 
} 

- (void)drawRect:(CGRect)rect 
{ 
    ... 
    for (int i = 0; i < currentPathIndex; i++) { 
    UIBezierPath *bezierPath = [availablePaths objectAtIndex:i]; 
    CGPathRef path = bezierPath.CGPath; 
    CGContextBeginPath(context); 
    CGContextAddPath(context, path); 
    CGContextDrawPath(context, kCGPathEOFill); 
    } 
    ... 
} 
+0

+1無需創建另一個CGMutablePathRef。不過,我想知道,我在這裏實際做錯了什麼。我假設'replaceObjectAtIndex:withObject'釋放前一個對象並保留新對象,對嗎? – roplacebo 2013-03-16 11:48:29

1

發現,我被釋放CGPath對象在另一個類中,我把它發給:

-(void) setPath: (CGPathRef) pathToSet forceClosed: (BOOL) fClosed 
{ 

    if(_path){ 
    CGPathRelease(_path); 
    } 
    _path = pathToSet; 
    CGPathRetain(_path); // <--- was missing 
} 

謝謝,R。

+0

這很有道理,很高興你明白了。它看起來很奇怪,因爲它是失敗的,因爲像以前一樣將任何'CFPathRef'強制轉換爲'id'。 – 2013-03-16 14:36:53

相關問題