CCSprite userObject具有意外的空值(cocos2d 3.2)

时间:2014-11-08 23:52:39

标签: ios objective-c cocos2d-iphone

我正在尝试将NSNumber对象保存为CCSprite的userObject属性,但由于某些我无法弄清楚的原因,此值正在更改为null。 CCSprite是在我的自定义CCNode的init方法中创建的:

@implementation MainScene {
    NSMutableArray *sprites;
    NSArray *imageFileNames;
}

-(id) init {
    self = [super init];
    if (self) {

        int spriteCount = 9;

        imageFileNames = @[@"ccbResources/clubs.png", @"ccbResources/cog.png", @"ccbResources/diamonds.png", @"ccbResources/dice.png", @"ccbResources/droplet.png", @"ccbResources/heart.png", @"ccbResources/pacman.png", @"ccbResources/pawn.png", @"ccbResources/spades.png"];

        sprites = [NSMutableArray arrayWithCapacity:spriteCount];

        for (int i = 0; i < spriteCount; i++) {            
            CCSprite *sprite = [CCSprite spriteWithImageNamed:imageFileNames[i%imageFileNames.count]];
            [self addChild:sprite];
            sprite.scale = 1.8f;
            sprite.position = ccp(xPos, yPos);
            sprite.color = [CCColor colorWithRed:arc4random_uniform(255)/255.0f green:arc4random_uniform(255)/255.0f blue:arc4random_uniform(255)/255.0f];
            sprite.userObject = [NSNumber numberWithInt:i];

            [sprites addObject:sprite];

            CCLog(@"%@", sprite.userObject); // outputs the value of i, as intended
        }

    }
    return self;
}

在init方法结束时,当我打印出sprite.userObject的值时,它等于i,因此NSNumber成功保留为精灵的userObject属性。

但是在更新方法期间,由于某种原因,该值变为null:

-(void) update:(CCTime)delta {
    for (CCSprite *sprite in sprites) {
        CCLog(@"%@", sprite.userObject);
        // outputs "(null)" on the first update,
        // and outputs the value of newSpriteType on subsequent updates

        int newSpriteType = arc4random_uniform( (u_int32_t)imageFileNames.count );
        sprite.userObject = [NSNumber numberWithInt:newSpriteType];
    }
}  

我无法弄清楚为什么第一次调用update时sprite.userObject的值始终为null,并且在{{1}内为其分配新的NSNumber之前保持为null }} 方法。这尤其令人困惑,因为updatesprite.userObject方法中为其分配了有效的NSNumber,并且此值不会在init内部以外的任何位置更改或读取方法

0 个答案:

没有答案