12

I have code:

NSMutableArray *vertices = [[NSMutableArray alloc] init];

//Getting mouse coordinates
loc = [self convertPoint: [event locationInWindow] fromView:self];
[vertices addObject:loc]; // Adding coordinates to NSMutableArray

//Converting from NSMutableArray to GLfloat to work with OpenGL
int count = [vertices count] * 2; // * 2 for the two coordinates of a loc object
GLFloat []glVertices = (GLFloat *)malloc(count * sizeof(GLFloat));
int currIndex = 0;
for (YourLocObject *loc in vertices) {
    glVertices[currIndex++] = loc.x;
    glVertices[currIndex++] = loc.y;        
}

loc is CGPoint, so i need somehow to change from CGPoint to NSValue to add it to NSMutableArray and after that convert it back to CGPoint. How could it be done?

hockeyman
  • 1,141
  • 6
  • 27
  • 57

1 Answers1

20

The class NSValue has methods +[valueWithPoint:] and -[CGPointValue]? Is this what you are looking for?

//Getting mouse coordinates
NSMutableArray *vertices = [[NSMutableArray alloc] init];
CGPoint location = [self convertPoint:event.locationInWindow fromView:self];
NSValue *locationValue = [NSValue valueWithPoint:location];
[vertices addObject:locationValue];

//Converting from NSMutableArray to GLFloat to work with OpenGL
NSUInteger count = vertices.count * 2; // * 2 for the two coordinates
GLFloat GLVertices[] = (GLFloat *)malloc(count * sizeof(GLFloat));
for (NSUInteger i = 0; i < count; i++) {
    NSValue *locationValue = [vertices objectAtIndex:i];
    CGPoint location = locationValue.CGPointValue;
    GLVertices[i] = location.x;
    GLVertices[i] = location.y;
}
Community
  • 1
  • 1
Vadim
  • 9,383
  • 7
  • 36
  • 58
  • I tried `NSValue *cgpointObj = [NSValue valueWithPoint:loc];`. But how to convert back to CGPoint? – hockeyman Jul 04 '12 at 10:36
  • 1
    Something like `CGPoint loc = cgpointObj.pointValue` should work. I added updated code. – Vadim Jul 04 '12 at 10:38
  • I think its not adding any values. If I write code:| `NSUInteger sum = vertices.count; NSLog(@"count: %lu", sum);` It always writes that sum = 0. Why? No values have been added? Then why haven't they been added? – hockeyman Jul 04 '12 at 13:45
  • 1
    You would better to run Debugger, trace all code and look into variables. – Vadim Jul 04 '12 at 15:55
  • 17
    To convert an NSValue back to a CGPoint this worked for me: `CGPoint tempPoint = tempValue.CGPointValue;` – crgt Aug 24 '12 at 22:58
  • 2
    @crgt: That's on iOS. `pointValue` is the correct method on the Mac. – Peter Hosey Feb 18 '13 at 05:17