如何在实例方法中访问Class方法变量或者为两者使用公共变量?

时间:2015-07-31 07:04:54

标签: ios objective-c class sprite-kit instance

我有这个Class方法来创建一个英雄对象。

+(id)hero
{
    NSArray *heroWalkingFrames;
    //Setup the array to hold the walking frames
    NSMutableArray *walkFrames = [NSMutableArray array];
    //Load the TextureAtlas for the hero
    SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
    //Load the animation frames from the TextureAtlas
    int numImages = (int)heroAnimatedAtlas.textureNames.count;
    for (int i=1; i <= numImages/2; i++) {
        NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
        SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
        [walkFrames addObject:temp];
    }
    heroWalkingFrames = walkFrames;
    //Create hero sprite, setup position in middle of the screen, and add to Scene
    SKTexture *temp = heroWalkingFrames[0];

    Hero *hero = [Hero spriteNodeWithTexture:temp];
    hero.name =@"Hero";
    hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
    hero.physicsBody.categoryBitMask = heroCategory;
    hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;    
    return hero;
}

我有另一个实例方法为我的英雄执行运行动画。

-(void)Start
{
        SKAction *incrementRight = [SKAction moveByX:10 y:0 duration:.05];
        SKAction *moveRight = [SKAction repeatActionForever:incrementRight];
        [self runAction:moveRight];     
}

现在heroWalkingFrames方法中的Start变量,所以我可以执行动画,我想在Start方法中添加这一行

 [SKAction repeatActionForever:[SKAction animateWithTextures:heroWalkingFrames timePerFrame:0.1f resize:NO restore:YES]];

我有什么方法可以将这个变量用于两者?

1 个答案:

答案 0 :(得分:2)

当然,在Hero.h添加:

@property (nonatomic, retain) NSArray *walkingFrames;

然后,在+(id)hero方法中,使用:

,而不是声明新数组NSArray *heroWalkingFrames
+(id)hero
{
    //Setup the array to hold the walking frames
    NSMutableArray *walkFrames = [NSMutableArray array];
    //Load the TextureAtlas for the hero
    SKTextureAtlas *heroAnimatedAtlas = [SKTextureAtlas atlasNamed:@"HeroImages"];
    //Load the animation frames from the TextureAtlas
    int numImages = (int)heroAnimatedAtlas.textureNames.count;
    for (int i=1; i <= numImages/2; i++) {
        NSString *textureName = [NSString stringWithFormat:@"hero%d", i];
        SKTexture *temp = [heroAnimatedAtlas textureNamed:textureName];
        [walkFrames addObject:temp];
    }

    //We set hero texture to the first animation texture:
    Hero *hero = [Hero spriteNodeWithTexture:walkFrames[0]];
    // Set the hero property "walkingFrames"
    hero.walkingFrames = walkFrames;

    hero.name =@"Hero";
    hero.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:hero.size];
    hero.physicsBody.categoryBitMask = heroCategory;
    hero.physicsBody.categoryBitMask = obstacleCategory | groundCategory | homeCategory;    
    return hero;
}