hockeyman hockeyman - 1 year ago 136
Objective-C Question

CGPoint to NSValue and reverse

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;

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?

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download