无法向NSMutableArray添加对象

时间:2012-11-19 13:24:59

标签: objective-c chipmunk physics-engine

美好的一天! 我用物理引擎“花栗鼠”。尝试通过单击创建动态对象。 AddBalls()创建所需的主体和形状。通过单击它必须生成一个新对象并将其放在数组中。

-(void)AddBalls: (UIImageView *)image;
{
    cpBody *ball2Body = cpBodyNew(100.0, INFINITY);
    ball2Body->p = cpv(60, 250);
    cpSpaceAddBody(space, ball2Body);

    cpShape *ball2Shape = cpCircleShapeNew(ball2Body, 20.0, cpvzero);
    ball2Shape->e = 0.5;
    ball2Shape->u=0.2;
    ball2Shape->data = (__bridge void*)image;
    ball2Shape->collision_type = 1;
    cpSpaceAddShape(space, ball2Shape);

    [children addObject: (__bridge id)ball2Shape];//EXC_BAD_ACCESS code=1
}

-(void)setupChipmunk

{
    cpInitChipmunk();
    space = cpSpaceNew();
    space->gravity = cpv(0, -100);
    space->elasticIterations = 10;

    [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(tick:) userInfo:nil repeats:YES];

    cpBody *ballBody = cpBodyNew(100.0, INFINITY);
    ballBody->p = cpv(60,250);
    cpSpaceAddBody(space, ballBody);
    cpShape *ballShape = cpCircleShapeNew(ballBody, 20.0, cpvzero);
    ballShape->e = 0.5;
    ballShape->u = 0.8;
    (ballShape->data) =(__bridge void*) ball;
    ballShape->collision_type = 1;
    cpSpaceAddShape(space, ballShape);
}

-(void)tick:(NSTimer *)timer
{
    cpSpaceStep(space, 1.0f/60.0f);
    cpSpaceHashEach(space->activeShapes, &updateShape, nil);
}

-(void) updateShape (void *ptr, void *unused)
{
    cpShape *shape = (cpShape*)ptr;

    if(shape == nil || shape->body == nil || shape->data == nil) {
        NSLog(@"Unexpected shape please debug here...");
        return;
    }

    if([(__bridge UIImageView*)shape->data isKindOfClass:[UIView class]]) {
        [(UIView *)((__bridge UIImageView*)shape->data) setCenter:CGPointMake(shape->body->p.x, 480 - shape->body->p.y)];
    }
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (void)handleTap:(UITapGestureRecognizer *)sender {     
    if (sender.state == UIGestureRecognizerStateEnded) {
        [self AddBalls];
    }
}

方法AddBalls应该将新形状放入数组中。但我收到错误“EXC_BAD_ACCESS...”。我该怎么办?感谢

1 个答案:

答案 0 :(得分:2)

你不能只将任何类型转换为id,它实际上需要是Objective-C类型。您需要将ball2Shape包裹在NSValue

[children addObject:[NSValue value:&ball2Shape withObjCType:@encode(cpBody*)]];

...
//When you need to use/free the values
for (NSValue *value in children)
{
    cpBody *body = (cpBody*)[value pointerValue];

    //Use body like you did above.

    //Even though it is ARC you will need to free cpBody since
    // it is not an Objective-C object
    cpBodyFree(body);
}