Object-C / iPhone and Switch Statements
Lately (meaning the last year or so) I started to be a lousy blogger. Either I have nothing to say or I am so busy that I don’t have time for it. So this time where I started to develop and iPhone app for hire with a hard deadline leaving a lot of work to be done. So far the project progresses well and there is little head banging. Still I ran into an old strange issue with Object-C and wasted a few hours. Eventually I dawned on my that I had this issue beforehand and then it was fixed right away.
So what happened? I wanted to create an enum to store a flag of what the program should do next like display the row, display the row’s detail or query the server for data. That looked like this:
enum Actions {
row,
detail,
search
};
typedef enum Actions Actions;
Then I wanted to use it in a switch-case statement to execute the appropriate action:
switch( actions ) {
case search:
NSString *query = (NSString *) action.data;
return;
case detail:
childViewController = [[TestViewController alloc]
initWithNibName:@"TestDetail"
bundle:nil];
break;
default:
NSDictionary *venue = (NSDictionary *) action.data;
childViewController = [[Test2TableViewController alloc]
initWithRows:rows];
}
But then I get this error: Expected expression before NSString which looks wrong. I am not sure why but the fix is simple. One just needs to wrap each block between case ???: and break into a {} block. That’s it:
switch( actions ) {
case search:
{
NSString *query = (NSString *) action.data;
return;
}
case detail:
{
childViewController = [[TestViewController alloc]
initWithNibName:@"TestDetail"
bundle:nil];
}
break;
default:
{
NSDictionary *venue = (NSDictionary *) action.data;
childViewController = [[Test2TableViewController alloc]
initWithRows:rows];
}
}
Hope that helps - Andy
Comments are closed.