1

I have created an array of 16 CGpoints representing 16 positions on a game board. This is how i set up the array CGPoint cgpointarray[16]; I would like to create a for loop to cycle through each item in the array and check if the touch is within x distance of a position (i have the position as a CGPoint. I don't have much experiance with xcode or objective c. I know the python equivalent would be

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

How would i accomplish this? Thanks

Puregame
  • 11
  • 2

3 Answers3

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

Or if you want to use the NSArray Class:

NSMutableArray *points = [NSMutableArray array];

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

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

        //do something
}

( not tested in XCode )

CarlJ
  • 9,461
  • 3
  • 33
  • 47
  • meccan's answer is more complete. What I posted (and his top code segment) will work just fine, but using NSArray is the way I would go. – Andrew Madsen Jan 03 '12 at 16:22
  • the first one is the C Struct version (w/o OOP). The second one uses the standard Foundation Objects for storing Data. This is why @AndrewMadsen recommend the second solution. – CarlJ Jan 03 '12 at 16:42
  • 1
    NSArray is an Objective-C object. Whereas your original ccgpointarray is a regular C-style array. Both are completely valid in Objective-C, but NSArray is a little nicer to work with. It handles memory management for you, through it's NSMutableArray subclass can easily be resized to hold more objects, can easily be stored inside of other objects like dictionaries, etc. Also, the Cocoa and Cocoa-Touch APIs use NSArray all over the place. – Andrew Madsen Jan 03 '12 at 16:44
1

This should do it:

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

    // Do stuff with point
}
Andrew Madsen
  • 21,309
  • 5
  • 56
  • 97
0

I would normally go for the NSValue approach above but sometimes you are working with an API where you can't change the output. @Andrews approach is cool but I prefer the simplicity of .count:

NSArray* arrayOfStructyThings = [someAPI giveMeAnNSArrayOfStructs];
for (NSUInteger i = 0; i < arrayOfStructyThings.count; ++i) {
    SomeOldStruct tr = arrayOfStructyThings[i];
    .... do your worst here ...
}
Oly Dungey
  • 1,603
  • 19
  • 20