Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do my switch cases sometime need braces in Objective-C? [duplicate]

Tags:

objective-c

Sometimes Xcode will show an error "Expected expression" on the line after a case. For example, Xcode is pointing to UserContentViewController with a red arrow:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case IndexVideo: 
            UserContentViewController* detailViewController = [[UserContentViewController alloc] initWithUser:self.user];
            [self.navigationController pushViewController:detailViewController animated:YES];
            break;

    }
}

If I put braces around my case, the error is gone. Firstly, I want to know what is the problem with not using braces. I've never used braces in cases in any other language. Secondly, why does Xcode only complain about my cases on rare occasions? I can't quite discern what type of code triggers this error.

like image 426
Pwner Avatar asked Dec 09 '22 14:12

Pwner


1 Answers

Basically, if you want to declare a variable you need to add the braces to define scope.

ARC also adds some requirements (or, rather, stricter requirements) to define scope (so you may get a number of "switch case is in protected scope" errors to fix when upgrading an older codebase). This is because ARC needs to know in detail when a variable isn't / can't be referred to any more so that it can deal with the release correctly.

Everything relates back to giving the compiler enough information about the scope of declared variables. Should they be part of a single case, or multiple cases...

like image 181
Wain Avatar answered Jan 22 '23 02:01

Wain