the_underscore_key
the_underscore_key

Reputation: 117

multiple identical pointers, can't figure out why

I'm new to Objective-C, I feel like I'm probably just making a dumb mistake, but I have tried googling this with no luck (maybe I'm just not searching the right things)

Essentially, I tried to write my own object class, and then make several instances of it, but the data seems locked together; Changing the data for any one reference changes it for all of them.

here's where I make the objects and use them.

@implementation Drawing
//leaving many functions out as they are not part of the problem

Ball * balls[10];
int numPoints;

//this gets called first
- (id) initWithCoder: (NSCoder *)aDecoder
{
    //leaving out loading of images.....

    numPoints=10;
    for(int i=0; i<10; i++){
        balls[i]=[[Ball alloc] init];
        printf("bmem: %p\n",%balls[i]);
        float tpx=arc4random()%1024;
        float tpy=arc4random()%768;
        printf("randX: %f\n",tpx);
        printf("randY: %f\n",tpy);
        CGPoint tempPt = CGPointMake(tpx,tpy);
        printf("mem: %p\n",%tempPt);
        [balls[i] setLocation:tempPt];
    }
    //code to start a timer on the drawRect function....
}

//called regularly, every 30 seconds
- (void) drawRect:(CGRect)rect
{
    CGContextRef c=UIGraphicsGetCurrentContext();
    CGContextClearRect(c, rect);

    for(int i=0; i<numPoints; i++)
    {
        int ptX=[balls[i] getX];
        int ptY=[balls[i] getY];
        printf("index: %d\n",i);
        printf("x: %d\n",ptX);
        printf("y: %d\n",ptY);
        CGContextDrawImage(c, CGRectMake((int)ptX-WIDTH/2, (int)ptY-WIDTH/2, WIDTH, HEIGHT), image);
    }
}

This program outputs a series of numbers which I thought would be useful. - "bmem", or the point in memory where the ball is, increments by regular intervals, as expected. - "randX" and "randY" are completely random, as they should be. - "mem", or the point in memory with the CGPoint, doesn't change

and this is the ball object:

@implementation Ball
int x;
int y;

-(void)setLocation:(CGPoint)loc{
    x=loc.x;
    y=loc.y;
}

-(int)getX{
    return x;
}

-(int)getY{
    return y;
}

@end

At first I just though I had static attributes in the Ball class, but on googling I found out that objective-c does not have static attributes. I've blindly tried about a dozen different things with no success. I really just need this to work.

Upvotes: 1

Views: 66

Answers (1)

trojanfoe
trojanfoe

Reputation: 122401

You are using the global variables:

Ball * balls[10];
int numPoints;

When you probably want instance variables:

@interface Balls : NSObject
{
    Ball * balls[10];
    int numPoints;
}
...
@end

Upvotes: 2

Related Questions