Iphone 是否在NSMutableDictionary中存储CGMutablePathRef?

Iphone 是否在NSMutableDictionary中存储CGMutablePathRef?,iphone,objective-c,cocos2d-iphone,Iphone,Objective C,Cocos2d Iphone,我想在六边形精灵周围创建触摸区域(CGMutablePathRefs)。我的目标是创建名为hexTouchArea1、hexTouchArea2等的键,因此我开始将它们存储在NSMutableDictionary中。但我无法在其中存储CGMutablePathRefs。我该如何解决这个问题 for (int i = 0; i < hexCount; i++) { hexTouchAreas = [[NSMutableDictionary alloc] init];

我想在六边形精灵周围创建触摸区域(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);
}

和:如何将这些触摸区域分配给CCSprite,以便如果sprite旋转,它们不会单独移动?

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

NSValue *pathAsValue = [NSValue valueWithPointer:hexTouchArea];
[dictionary setObject:pathAsValue forKey:yourKeyHere];
需要时,请使用:

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

[hexTouchAreas setObject:hexTouchArea forKey:touchAreaKey];
致:

CGPath
CGMutablePath
只是不透明的
CFType
对象类型,这些对象类型可以(通过强制转换到
id
)添加到任何免费桥接到CoreFoundation计数器部件的Cocoa容器类中


然后观察从
drawHexagonTouchArea

返回的结果的内存泄漏。首先,您应该知道,在上面的代码中泄漏了两个cgmutablePathRef。如果使用
CGPathCreateMutable()
,则需要将其与
CGPathRelease()
匹配,否则该路径将永远不会被释放。此外,在循环中初始化
hexTouchArea
时不需要创建路径,因为您只需使用
-drawHexagontTouchArea:
的结果覆盖路径。链接问题处理NSMutableArray而不是NSMutableDictionary时,可能会重复,同样的原则也适用于这里。不过要小心——当字典被销毁时,将指针封装在
NSValue
中不会自动调用
CGPathRelease
。哈,不知道CFType被桥接到了NSObject,正如Ken在这里说的那样:。我只是假设这种转换只适用于显式免费桥接类型。
[hexTouchAreas setObject:hexTouchArea forKey:touchAreaKey];
[hexTouchAreas setObject:(id)hexTouchArea forKey:touchAreaKey];