1

我在使用 Objective C 时遇到问题。我在移动精灵后尝试调用块

我想要实现的简短版本是我想移动阵列中的所有敌人,当每个敌人完成移动时,我想检查它是否发生碰撞。

下面的简化代码显示了我正在尝试做的事情。

我的 Actor 类是这样定义的

// -----------------------------
// Actor.h

#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "ScreenObject.h"

typedef void (^actorMoveComplete)(void);

@interface Actor : ScreenObject
{
   // actorMoveComplete onMoveComplete;
}

@property (nonatomic) BOOL isMoving;
@property (readwrite, copy) actorMoveComplete onMoveComplete;
@property (nonatomic, retain) CCSprite* sprite;

-(void) moveTo:(CGPoint)targetPosition Speed:(float) speed withCallback:(actorMoveComplete)moveComplete;

@end

// -----------------------------
//  Actor.m
#import "Actor.h"

@implementation Actor

@synthesize onMoveComplete;
@synthesize sprite;

-(void) moveTo:(CGPoint)targetPosition Speed:(float) speed withCallback:(actorMoveComplete)moveComplete;
{
    onMoveComplete = moveComplete;

    id actionMove = [CCMoveTo actionWithDuration:speed position:targetPosition];
    id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)];
    [super.sprite runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
}

-(void) spriteMoveFinished:(id) sender
{
    isMoving = NO;
    if (onMoveComplete != nil)
        onMoveComplete();
}
@end

如您所见,我正在尝试将块存储在onMoveComplete参数中(我也在私有变量中尝试过),然后在精灵移动完成后调用它。

在我的调用类中,我正在遍历一堆演员(敌人),一旦移动完成,我想为每个演员调用这个匿名代码块:

{
   [self checkForCollision:enemy];
}

我的调用类看起来像这样。

//------------------------------
//
//  GameLayer.h

#import "cocos2d.h"
#import "Actor.h"

@interface GameLayer : CCLayerColor
{
}

@property (nonatomic, copy) NSMutableArray *enemies;

- (void) updateEnemies;
- (void) checkForCollision:(Actor*)actor;
- (BOOL) isMapGridClear:(CGPoint)mapGrid excludeActor:(Actor*)actor;

@end


//------------------------------
//  GameLayer.m

#import "GameLayer.h"


@implementation GameLayer

@synthesize enemies;

- (void) updateEnemies
{

    for (Actor *enemy in enemies)
    {
        //  
        CGPoint newPosition = [self getNewPosition:enemy]; /* method to figure out new position */

        [enemy moveDelta:ccp(dX, dY) Speed:enemySpeed withCallback:^{
            [self checkForCollision:enemy];
        }];
    }
}


- (void) checkForCollision:(Actor*)actor
{
    if (![self isMapGridClear:actor.gridPosition excludeActor:actor])
    {
        actor.isCrashed=YES;
        [actor loadSprite:self spriteImage:@"crashed.png"];
    }
}


- (BOOL) isMapGridClear:(CGPoint)mapGrid excludeActor:(Actor*)actor
{
    /* Actual method figures out if there was a collision    */
    return YES;
}

@end

不幸的是,当我调用 onMoveComplete 块时,我不断收到 EXC_BAD_ACCESS 错误有趣的是,如果我尝试在 moveTo 方法中调用该块,它可以工作(但我当然希望它在移动完成后触发)。

谁能帮我解决我做错的事情。我什至使用正确的机制吗?

(对于格式不佳、不完整的代码段表示歉意)

4

1 回答 1

2

您正确地将您的属性声明为副本,但是您将实例变量直接设置为块的地址,而不使用生成的访问器。这意味着该块在被调用之前不会被复制并被销毁。

使用分配你的块self.onMoveCompleted = moveCompleted,你会没事的。

于 2012-05-19T08:04:03.543 回答