开发者

How to create and maintain multiples of the same object in Objective-C?

开发者 https://www.devze.com 2023-03-15 04:56 出处:网络
I\'m trying to get multiple Ball objects to form on screen and bounce around.I have it working fine for one, but I am having problems adding more.Ideally, the amount of balls will vary, but for now I

I'm trying to get multiple Ball objects to form on screen and bounce around. I have it working fine for one, but I am having problems adding more. Ideally, the amount of balls will vary, but for now I am trying to just get two into an array to change the rest of the code.

My problem is that everything compiles and runs fine, but I still only have one ball. This is where I suspect the problem arises.

I also feel like doing this in viewDidLoad is incorrect, but I'm not sure where it actually belongs.

viewDidLoad:

- (void)viewDidLoad {
[super viewDidLoad];

balls = [[NSMutableArray alloc] init];
CGPoint newPos = CGPointMake(5,5);

for(int i = 0; i < 2; i++) {
[balls addObject:[[[Ball alloc] init] autorelease]];
}

[[balls objectAtIndex:1] setPosition:newPos];

[NSTimer scheduledTimerWithTimeInterval:1.0 / 30.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];

}

- (void)onTimer
{
for(int i = 0; i < [balls count]; i++) {
    Ball *b = [balls objectAtIndex:i];
    [b update];
    [(BallView *)self.view refresh:b]开发者_Go百科;
    }
}


- (void)refresh:(Ball *)aBall {
ball = aBall;
[self setNeedsDisplay];

}

I've added my onTimer, I thought adding the delay in creating the balls would be enough to make this a nonissue. All update does is change the velocity/direction based on the accelerometer/collisions with the edge of the screen.


Indeed both balls should be displayed. Check their coordinates to see if they overlap. On another note, it appears you are leaking the balls array, as well as the ball1 and ball2 objects. You are alloc init'ing them so you have to release them at the end of viewDidLoad, or, if you are using retain properties, just autorelease them when you set them so that they get retained by the properties.

As for where the code should be located, viewDidLoad should be ok, but consider putting the balls array into the init method you call to create your ViewController, since there's probably no way your ViewController could work without that array being set up.

0

精彩评论

暂无评论...
验证码 换一张
取 消