【问题标题】:Store CGMutablePathRef in NSMutableDictionary ?将 CGMutablePathRef 存储在 NSMutableDictionary 中?
【发布时间】:2011-12-05 19:58:38
【问题描述】:

我想在我的六边形精灵周围创建触摸区域 (CGMutablePathRefs)。我的目标是创建名称为 hexTouchArea1、hexTouchArea2 等的键,因此我开始将它们存储在 NSMutableDictionary 中。但我不能在其中存储 CGMutablePathRefs。我将如何解决问题?

for (int i = 0; i < hexCount; i++) {
            hexTouchAreas = [[NSMutableDictionary alloc] init];
            CGPoint touchAreaOrigin = ccp(location.x -22, location.y-40);
            NSString *touchAreaKey = [NSString stringWithFormat:@"hexTouchArea%d",i];
            CGMutablePathRef hexTouchArea = CGPathCreateMutable();
            hexTouchArea = [self drawHexagonTouchArea:touchAreaOrigin];

            [hexTouchAreas setObject:hexTouchArea forKey:touchAreaKey];
            NSLog(@"the touchareas are %@", hexTouchAreas);
}

drawHexagonTouchArea 返回一个 CGMutablePathRef :

-(CGMutablePathRef) drawHexagonTouchArea:(CGPoint)origin
{

    CGMutablePathRef path = CGPathCreateMutable();
    CGPoint newloc = CGPointMake(origin.x, origin.y);

    CGPathMoveToPoint(path, NULL, newloc.x, newloc.y);
    CGPathAddLineToPoint(path, NULL, newloc.x -22,newloc.y + 38);
    CGPathAddLineToPoint(path, NULL, newloc.x + 0, newloc.y + 76);
    CGPathAddLineToPoint(path, NULL, newloc.x + 46,  newloc.y + 76);
    CGPathAddLineToPoint(path, NULL, newloc.x +66,newloc.y + 40);
    CGPathAddLineToPoint(path, NULL, newloc.x +44, newloc.y + 0);
    CGPathCloseSubpath(path);
    return path;
}

AND : 如何将这些触摸区域分配给 CCSprites,这样如果精灵旋转,它们就不会单独移动?

【问题讨论】:

  • 首先,您应该知道您在上面的代码中泄漏了两个 CGMutablePathRefs。如果您使用CGPathCreateMutable(),则需要将其与CGPathRelease() 匹配,否则路径将永远不会被释放。此外,无需在循环内的hexTouchArea 初始化中创建路径,因为您只需用-drawHexagonTouchArea: 的结果覆盖它。
  • 虽然链接的问题处理的是 NSMutableArray 而不是 NSMutableDictionary,但这里也适用相同的原则。

标签: iphone objective-c cocos2d-iphone


【解决方案1】:

可以使用NSValue封装CGMutablePathRef,然后添加到字典中:

NSValue *pathAsValue = [NSValue valueWithPointer:hexTouchArea];
[dictionary setObject:pathAsValue forKey:yourKeyHere];

当你需要得到它时,使用:

NSValue *myPathAsValue = [dictionary objectForKey:yourKeyHere];
CGMutablePathRef pathRef = [myPathAsValue pointerValue];

【讨论】:

  • 对此要小心——当字典被销毁时,在NSValue 中封装一个指针不会自动调用CGPathRelease
【解决方案2】:

变化:

[hexTouchAreas setObject:hexTouchArea forKey:touchAreaKey];

到:

[hexTouchAreas setObject:(id)hexTouchArea forKey:touchAreaKey];

CGPathCGMutablePath 只是不透明的CFType 对象类型,可以将它们添加(通过转换为id)到任何可免费桥接到其CoreFoundation 对应部分的Cocoa 容器类中。

并注意从drawHexagonTouchArea 返回的结果的内存泄漏

【讨论】:

  • 嗯,不知道 CFType 被桥接到 NSObject,正如 Ken 在这里所说:stackoverflow.com/a/1392445/19679。我只是假设这种转换只适用于明确的免费桥接类型。
猜你喜欢
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多