0

I can't understand why this works with if statement and not switch:

if ((int)typeOfHall == 1) {//LocalHall
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Game"];
    NSPredicate *p = [NSPredicate predicateWithFormat:@"player_id == %@ ",[[NSUserDefaults standardUserDefaults] valueForKey:@"LoggedUserId"]];
    request.predicate = p;
}

The code bellow it will not work (compile error: Expected expression (on NSFetchRequest)):

switch ((int)typeOfHall) {
    case 1:
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Game"]; //Error Expected expression
        NSPredicate *p = [NSPredicate predicateWithFormat:@"player_id == %@ ",[[NSUserDefaults standardUserDefaults] valueForKey:@"LoggedUserId"]];
        request.predicate = p;
        break;
    default:
        break;             
}

I don't know why this happens. I suppose that switch and if statements are similar, but in this case it seems that are very different.

Do you have any clue why this happens?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
ePascoal
  • 2,362
  • 6
  • 26
  • 44
  • doesn't work how? the case is ignored? it goes down the default branch? – Marc B Aug 26 '16 at 16:39
  • I putted a error on the line where occurs which is on NSFetchRequest statement. Anyway i edited the question and put between brackets what error raised – ePascoal Aug 26 '16 at 16:43
  • 2
    You say "I don't know why this happens." Why WHAT happens? You say it "doesn't work" but don't tell us what goes wrong. Does it fail to compile? Does it give the wrong result? If you want help with your code you have to post a coherent question. – Duncan C Aug 26 '16 at 16:44
  • as you can see above (Error: Expected expression (on NSFetchRequest)): . ok it is a compile error i will edit my question. – ePascoal Aug 26 '16 at 16:46

1 Answers1

5

You need a separate scope in the case if you want to declare any variables there:

switch ((int)typeOfHall) {
    case 1:
    {   /* Introduce a scope ... */
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Game"]; 
        NSPredicate *p = [NSPredicate predicateWithFormat:@"player_id == %@ ",[[NSUserDefaults standardUserDefaults] valueForKey:@"LoggedUserId"]];
        request.predicate = p;
        break;
    }   /* ... that ends here. */
    default:
        break;

}

Side note: if LocalHall is an enum value, your code is more readable without the cast:

switch (typeOfHall) {
    case LocalHall:
    // ...
molbdnilo
  • 64,751
  • 3
  • 43
  • 82