0

I'm working on an iPhone app and in my app there's an object that moves from the top to the bottom of the screen. To do this I use a CADisplay link. Once the object leaves the screen it is supposed to restart its route. The problem that I'm encountering is that each time the object restarts its route, it speeds up. This continues until the object is going so fast that you can barely see it. Any ideas why this is happening and how to stop it? Any help is appreciated, thanks in advance!

-(void)spawnButton{

int x = (arc4random() % (240) + 40;
int y = -100;

button1.center = CGPointMake(x,y);

displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(moveObject)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];

}



-(void) moveObject {

int z = 1;


button1.center = CGPointMake(button1.center.x , button1.center.y +z);



if (button1.center.y >= 480) {

    [self spawnButton];

}
}
Dave123
  • 306
  • 2
  • 4
  • 13

2 Answers2

1

You are creating a new display link on each call to spawnButton. If you're not doing anything to remove the old display link from the run loop, then the old display link will continue sending moveObject: messages. So after two calls to spawnButton you will get two moveObject: messages per video frame, and after three calls you will get three moveObject: messages per video frame, and so on.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
0

I seem to have solved the problem by invalidating the display link each time I restart the objects route.

if (button1.center.y >= 480) {

[self spawnButton];


[displaylink invalidate];

}
}
Dave123
  • 306
  • 2
  • 4
  • 13