Reputation: 493
I'm tidying up my first app, trying to combine my button press events into one method call and use the Tag of the button to see which one has been clicked. However, the switch statement doesn't seem to like me trying to alloc a view controller inside it
#import "NewsViewController.h"
...
...
- (IBAction)contentPressed:(id)sender
{
// check which button was pressed
UIButton *contentBtn = (UIButton *)sender;
switch (contentBtn.tag)
{
case 1:
NewsViewController *controller = [[NewsViewController alloc] initWithNibName:@"NewsViewController" bundle:nil];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
break;
}
}
It's refusing to acknowledge the controller - I get "Use of undeclared identifier 'controller'" and "unexpected interface name NewsViewController, identifier expected" on the line where I'm doing the alloc.
Everything worked before I tried to combine the separate IBActions for the buttons into one. Anyone shed any light on this?
Upvotes: 1
Views: 293
Reputation: 112857
In order to declare variables inside a switch switch statement that section of code must have it's own scope by enclosing in curly brackets.
switch (contentBtn.tag)
{
case 1:
{
NewsViewController *controller = [[NewsViewController alloc] initWithNibName:@"NewsViewController" bundle:nil];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
}
break;
}
Upvotes: 1
Reputation: 5157
You cannot declare variables directly within the case statement. You either have to declare the variable NewsViewController *controller
before the switch statement or enclose your complete case with curly braces. This stems from the fact, that case statements have a mechanism called fall-through where one case that does not end in break;
will continue through to the next case which creates difficulties with variable declarations. If you do it like this you should be fine:
switch (contentBtn.tag)
{
case 1:
{
NewsViewController *controller = [[NewsViewController alloc] initWithNibName:@"NewsViewController" bundle:nil];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
break;
}
}
Upvotes: 1