如何使用ARC从另一个类向CCArray添加对象

时间:2012-11-21 16:57:16

标签: ios cocos2d-iphone automatic-ref-counting

我需要将代码转换为ARC。我有一个CCArray用于绘制路径。我从另一个类填充CCArray值的对象。

问题是转换为ARC后,CCArray始终返回null

我看不出我做错了什么。

Ladybug.h

@interface Ladybug : CCSprite <CCTargetedTouchDelegate>{

    CCArray *linePathPosition;
}
@property (nonatomic, strong) CCArray *linePathPosition;

@end

Ladybug.m

@synthesize linePathPosition;

-(id) init
{
    if( (self=[super init] )) {
        self.linePathPosition = [[CCArray alloc] init];

    }
    return self;
}
-(void) updatePosition:(CGPoint) position
{
    [self.linePathPosition addObject:[NSValue valueWithCGPoint:position]];
    NSLog(@"line path %@",linePathPosition);
}
-(void) breakMoveLadyBug
{
    [self.linePathPosition removeAllObjects];
}

在主.m

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
    Ladybug *ladybug1 = (Ladybug *)[self getChildByTag:99];
    CCMotionStreak* streak = (CCMotionStreak *)[self getChildByTag:999];
    CGPoint touchLocation = [touch locationInView: [touch view]];
    CGPoint curPosition = [[CCDirector sharedDirector] convertToGL:touchLocation];

    if (ladybug1.isSelected) {

        streak.position = curPosition;
        [ladybug1 updatePosition:curPosition];
                NSLog(@"Cur position %@",NSStringFromCGPoint(curPosition));

        if (!ladybug1.isMoving) {

            [ladybug1 startMoveLadyBug];
        }
    }
}

日志:

 Cur position {331, 110}
 line path (null)

我做错了什么?使用ARC定义和初始化CCArray的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

这不是ARC或CCArray的问题。问题在于你对objective-c的理解。

要解决您的问题,请执行此行[self addChild:ladybug1 z:999 tag:99]。这样做:

Ladybug *ladybug1 = [[Ladybug alloc] init];
[self addChild:ladybug1 z:0 tag:99];

注意:这是在ccTouchMoved函数之外完成的,在一些将瓢虫对象添加到场景/图层的函数中。

然后你的ccTouchMoved函数会有一个已分配的瓢虫对象。

问题在于,如果你从未在瓢虫对象上调用init函数,CCArray永远不会被分配,所以一切都将为null。然后,您将尝试将点添加到空数组,这将不执行任何操作。你可以做你想要的所有这些标签(我个人不知道你为什么这样做),但是你需要为瓢虫对象指定标签。所以将它添加到CCLayer / CCScene(您正在使用),并设置其标记。然后,您可以使用getChildByTag函数。