Sabha B
Sabha B

Reputation: 2089

Objective C Float value is converted internally - no idea why

Am writing a game using cocos 2d which involves lot of Float type properties to determine the vertices(x,y) of my shapes (Square , Triangle). I have a Shape class which simply holds the total number of vertices(int) and the vertices (CGFloat*). I have one more class called ShapeHolder which defines the values for different types of shapes , it has the properties called Shape square; and Shape Triangle. In the ShapeHolder init am storing(hard coding) the vertices information(x,y) as follows , am also printing the values immediately after the definition which works perfectly

          CGPoint _square[] = {
        CGPointMake(100.0f, 100.0f) , 
        CGPointMake(200.0f, 100.0f) , 
        CGPointMake(200.0f, 200.0f) , 
        CGPointMake(100.0f, 200.0f)
    };. 
            square = [[[Shape alloc] initWithVerticesLength: 4] retain];
        square.vertices = _square;
        for (int i = 0; i< square.count; i++) {
            NSLog(@"Init Square Vertices X Y = %f , %f" , square.vertices[i].x ,square.vertices[i].y );
        }
        triangle = [[[Shape alloc] initWithVerticesLength: 3] retain];
        triangle.vertices = _triangle;

The problem am having is on while retrieving the same values in my OpenGL drawing class to render different shapes , here is the code

        allShapes = [[ShapeHolder alloc] init];
        for (int i = 0; i< allShapes.square.count; i++) {
            NSLog(@"Main Square Vertices X Y = %f , %f" , [[allShapes square]vertices][i].x ,[[allShapes square] vertices][i].y );

        }

The value is converted somehow , no idea why please clarify. Am not getting any runtime errors or compile time error which is really bothering my knowledge

Init Square Vertices X Y = 100.000000 , 100.000000 
Init Square Vertices X Y = 200.000000 , 100.000000 
Init Square Vertices X Y = 200.000000 , 200.000000 
Init Square Vertices X Y = 100.000000 , 200.000000 

Main Square Vertices X Y = 100.000000 , 100.000000 
Main Square Vertices X Y = -1.998910 , 0.000000 
Main Square Vertices X Y = 0.000000 , 0.000000 
Main Square Vertices X Y = -1.998912 , 0.000000

Upvotes: 0

Views: 258

Answers (1)

Warren Burton
Warren Burton

Reputation: 17378

Looks like you are doing a shallow copy of the array pointer for _square. You need to be doing a deep copy of the vertices into a member array in your object.

The reason your first vertex isn't being changed is that your class is keeping the pointer to the first point in the array. Subsequent vertices in the array are being reclaimed by the memory manager and reused. Possibly luck too.

Upvotes: 1

Related Questions