2011-12-05 50 views
0

我想在我的六邊形小精靈周圍創建觸摸區域(CGMutablePathRefs)。我的目標是創建名稱爲hexTouchArea1,hexTouchArea2等的鍵,所以我開始將它們存儲在NSMutableDictionary中。但我無法在其中存儲CGMutablePathRefs。我將如何解決這個問題?在NSMutableDictionary中存儲CGMutablePathRef?

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; 
} 

和:我如何分配這些觸摸區域CCSprites所以如果精靈旋轉時,他們不單獨移動?

+0

首先返回,你應該知道,你在漏水上述兩個代碼CGMutablePathRefs。如果使用'CGPathCreateMutable()',則需要將其與'CGPathRelease()'匹配,否則路徑將永遠不會被釋放。另外,不需要在循環內的'hexTouchArea'初始化中創建路徑,因爲您只需使用'-drawHexagonTouchArea:'的結果覆蓋它即可。 –

+0

[CGMutablePathRef到NSMutableArray]的可能的重複(http://stackoverflow.com/questions/4133063/cgmutablepathref-to-nsmutablearray) –

+0

雖然鏈接的問題處理NSMutableArray而不是NSMutableDictionary,但同樣的原則適用於此處。 –

回答

1

您可以使用NSValue封裝CGMutablePathRef,然後將其添加到字典:

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

當你需要得到它,使用:

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

注意這一點,雖然 - 在'NSValue'中封裝指針不會在字典被銷燬時自動調用'CGPathRelease'。 – duskwuff

1

變化:

[hexTouchAreas setObject:hexTouchArea forKey:touchAreaKey]; 

發送至:

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

CGPathCGMutablePath只是不透明CFType對象類型,以及那些可以添加(通過鑄造到id)轉換爲免費電話橋接它們的CoreFoundation反份可可任何容器類。

,看結果的內存泄漏從drawHexagonTouchArea

+0

呵呵,不知道CFType被橋接到NSObject,正如Ken在這裏所述:http://stackoverflow.com/a/1392445/19679。我只是假設這個投射只能用於明確免費的橋接類型。 –

相關問題