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

发布于 2024-09-12 12:05:44 字数 378 浏览 0 评论 0原文

// 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]];
    }
}

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

// 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]];
    }
}

Where do I declare index in my header file and how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

高冷爸爸 2024-09-19 12:05:44

如果 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 作为 ivar,例如

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

在构造实例时自动初始化为 0,并且除 next 之外的方法都可以使用 索引。此外,每个实例都有自己的索引

If index is used only within the -next method, you can define a static variable.

- (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]];
    }
}

Note that all instances will share the same index.

But I believe it's better to make index as an ivar, e.g.

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

it is automatically initialized to 0 when the instance is constructed, and methods other than next can use the index. Also, each instance will have its own index.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文