2012-01-03 32 views
1

我創建了一個由16個CGpoints組成的數組,代表遊戲板上的16個位置。這是我如何設置陣列CGPoint cgpointarray[16];我想創建一個循環來循環數組中的每個項目,並檢查觸摸是否在一個位置的x距離內(我的位置是CGPoint,我不。有和Xcode或目標C多的experiance我知道蟒蛇相當於將如何在CGPoint數組中循環

for (i in cgpointarray){ 
     //Stuff to do 
    } 

我將如何做到這一點感謝

回答

5
for (int i = 0; i < 16; i++){ 
     CGPoint p = cgpointarray[i]; 
     //do something 
    } 

或者,如果你想使用NSArray類:

NSMutableArray *points = [NSMutableArray array]; 

[points addObject:[ NSValue valueWithCGPoint:CGPointMake(1,2)]]; 

for(NSValue *v in points) { 
     CGPoint p = v.CGPointValue; 

     //do something 
} 

(XCode中未測試)

+0

meccan的答案更完整。我發佈的內容(以及他的頂級代碼段)都可以正常工作,但使用NSArray是我的方式。 – 2012-01-03 16:22:17

+0

爲什麼?有什麼不同? – Puregame 2012-01-03 16:29:52

+0

第一個是C Struct版本(不帶OOP)。第二個使用標準的基礎對象來存儲數據。這就是@AndrewMadsen推薦第二種解決方案的原因。 – CarlJ 2012-01-03 16:42:33

1

這應做到:

for (NSUInteger i=0; i < sizeof(cgpointarray)/sizeof(CGPoint); i++) { 
    CGPoint point = cgpointarray[i]; 

    // Do stuff with point 
} 
0

我通常會去上面的NSValue的方法,但有時你與一個API,你不能改變輸出工作。 @Andrews的方法很酷,但我更喜歡.count的簡單性:

NSArray* arrayOfStructyThings = [someAPI giveMeAnNSArrayOfStructs]; 
for (NSUInteger i = 0; i < arrayOfStructyThings.count; ++i) { 
    SomeOldStruct tr = arrayOfStructyThings[i]; 
    .... do your worst here ... 
}