Search code examples
iphoneobjective-csdkdeclare

How do I declare index=0 in .h file iPhone


// 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?


Solution

  • 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.