如何在.h文件iPhone中声明index = 0

时间:2010-08-01 11:29:37

标签: iphone objective-c sdk declare

// Declare index in Header.h

index=0;

- (IBAction)next {
    index++;
    // Set imageCount to as many images as are available
    int imageCount=2;
    if (index<=imageCount) {
        NSString* imageName=[NSString stringWithFormat:@"img%i", index];
        [picture setImage: [UIImage imageNamed: imageName]];
    }
}

我在哪里声明头文件中的索引以及如何?

1 个答案:

答案 0 :(得分:2)

如果仅在index方法中使用-next,则可以定义静态变量。

- (IBAction)next {
    static int index = 0;    // <-- here
    index++;
    // Set imageCount to as many images as are available
    int imageCount=2;
    if (index<=imageCount) {
        NSString* imageName=[NSString stringWithFormat:@"img%i", index];
        [picture setImage: [UIImage imageNamed: imageName]];
    }
}

请注意,所有实例都将共享相同的index

但我认为最好将index作为ivar,例如

@interface ... {
   ...
   int index;
   ...
}

构造实例时会自动初始化为0,而next以外的方法可以使用index。此外,每个实例都有自己的index