0

我正在尝试沿路径动态绘制曲线以表示山脉。

我有一个返回 a 的函数CGPathRef,它是一个指向结构的 C 指针。

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

然后我CGPathRefs通过将它们包装在一个UIBezierPath.

-(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);

在我重复这个动作序列几次后,我的程序中断并显示给我。

带有 EXC_BAD_ACCESS 代码 = 2 的 UIApplicationMain。

我知道有内存泄漏。

CGPathRef我的问题是,当我最终将它传递给几个函数并将它包装在另一个类中时,我该如何处理?

我更新了代码,现在收到 EXC_I386_GPFLT 错误。

4

2 回答 2

1

我看到三个问题。

  1. 我不是很熟悉SKShapeNode,但从文档看来它只是使用你给它的路径而不复制它(不像UIBezierPath)。在这种情况下,您需要从UIBezierPath's中复制路径CGPathRef,否则一旦 's 被释放,它将被UIBezierPath释放。例如:

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

    完成形状节点后,您可能需要取消分配该路径:

    CGPathRelease(node.path);
    
  2. 看起来您发布的代码中有一些内存泄漏:您正在创建CGPathRefs in newPath,将它们复制到 a UIBezierPathin otherFunction,并且从不删除它们。这不会导致你的问题,但它可能会导致其他人在路上。:)

  3. 我会小心命名带有前缀的方法,new因为这对 Objective-C 有一定的意义(见这里)。试试createPath吧。

于 2016-01-11T14:12:10.630 回答
0

编译器的问题是,如果你用 newXXX 命名一个函数,你需要管理你的内存。所以在 -otherFunction

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

创建 UIBezierPath 后,您应该调用

CGPathRelease(ref);
于 2016-01-11T14:07:15.550 回答