2016-01-11 42 views
0

我試圖動態繪製沿路徑曲線試圖表示山。SKShapeNode和CGPathRef EXC_BAD_ACCESS

我有一個函數返回一個CGPathRef,它是一個C指向結構的指針。

-(CGPathRef)newPath 
{ 
    CGMutablePathRef mutablePath = CGPathCreateMutable(); 
    //inserting quad curves, etc 
    return mutablePath; 
} 

我然後通過在UIBezierPath包裹周圍通過這些CGPathRefs

-(NSArray*)otherFunction 
{ 
    CGPathRef ref = [self newPath]; 
    UIBezierPath *path = [UIBezierPath bezierPathWithCGPath: ref]; 
    NSArray* paths = @[path]; 
    CGPathRelease(ref); 
    return paths; 
} 

我然後採取的路徑返回的數組,並使用他們SKShapeNode顯示到屏幕上。

SKShapeNode *node = [SKShapeNode new]; 

NSArray* paths = [self otherFunction]; 
CGPathRef ref = [[paths firstObject] CGPath]; 

node.path = ref; 
node.fillColor = [UIColor orangeColor]; 
node.lineWidth = 2; 

最後。

[self addChild:node]; 
CGPathRelease(node.path); 

當我重複這個動作序列幾次後,我的程序就會中斷並顯示出來。

UIApplicationMain與EXC_BAD_ACCESS代碼= 2

我知道有內存泄漏。

我的問題是如何處理釋放CGPathRef當我最終通過幾個函數並將它包裝在另一個類中?

我更新了代碼,現在收到EXC_I386_GPFLT錯誤。

+0

我建議你發佈編譯的實際代碼,而不是「從其他函數解開的路徑」。 – 0x141E

回答

1

我看到三個問題。

  1. 我不是很熟悉SKShapeNode,但是從文檔,它看起來像它只是使用你給它的路徑,而不復制它(不像UIBezierPath)。在這種情況下,您需要複製UIBezierPathCGPathRef以外的路徑,否則一旦UIBezierPath發佈,它將被重新分配。例如:

    SKShapeNode *node = [SKShapeNode new]; 
    CGPathRef pathCopy = CGPathCreateCopy(/* path from other function unwrapped */); 
    node.path = pathCopy; 
    ... 
    

    您可能需要解除對其路徑當你與形狀節點完成:

    CGPathRelease(node.path); 
    
  2. 看起來你對你發佈的代碼一些內存泄漏:您在newPath中創建了CGPathRef s,將它們複製到otherFunction中的UIBezierPath,並且從不刪除它們。這不會導致你的問題,但它可能會導致其他人在路上。:)

  3. 我會小心命名方法,前綴爲new,因爲這對Objective-C有一定的含義(請參閱here)。改爲嘗試createPath

0

編譯器的事情是,如果你用newXXX命名一個函數,你需要管理你的內存。所以在-otherFunction

-(NSArray*)otherFunction 
{ 
    CGPathRef ref = [self newPath]; 
    UIBezierPath *path = [UIBezierPath bezierPathWithCGPath: ref]; 
    NSArray* paths = @[path]; 
    return paths; 
} 

創建UIBezierPath後,你應該叫

CGPathRelease(ref);