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

How I can access Class method variable in instance method OR Use a common variable for both?

我有这个 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]];

有什么方法可以同时使用这个变量吗?

当然可以,在 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;
}