I am creating (the user pressing a button) many UIImageViews programmly, and assigning a tag to each when created in this way:
int a;
if (a != nil){
a = 0;
}
a = a + 1;
image1.tag = a;
the problem is that with a = a +1 I would like the variable to increase: 1,2,3,4… but it remains always 1, so each Image has a tag of 1. if I add a++, the tag 2 is assigned to all. why?? Thanks for the answer
This is assuming a is a simple type.
Firstly you should never compare a simple type like so;
However, the if statement above will always be true after the first button is pressed because a will be > 0 and therefore will not evaluate to NULL. So your if statement will always reset a back to zero. If you want the tag to increment remove that if statement.
Assuming a is not a simple type.
Make a an int and also remove the if statement. Heres is some supporting code.
@implementation ViewController{ int a; } -(void)pressed{ a = a + 1; NSLog(@"%d",a); } - (void)viewDidLoad{ [super viewDidLoad]; a = 0; UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect]; b.frame = CGRectMake(0, 0, 100, 50); [b addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:b]; } @end