【问题标题】:Objective-C if vs switch [duplicate]Objective-C if vs switch [重复]
【发布时间】:2017-01-03 09:39:20
【问题描述】:

我不明白为什么这适用于if 语句而不是switch

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

下面的代码不起作用(编译错误:Expected expression(在 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;             
}

我不知道为什么会这样。我认为 switch 和 if 语句是相似的,但在这种情况下,它似乎非常不同。

你知道为什么会发生这种情况吗?

【问题讨论】:

  • 不起作用怎么办?案件被忽略?它进入默认分支?
  • 我在 NSFetchRequest 语句中发生的行上放了一个错误。无论如何,我编辑了问题并将引发的错误放在括号内
  • 你说“我不知道为什么会这样。”为什么会发生什么?您说它“不起作用”,但不要告诉我们出了什么问题。编译失败了吗?它会给出错误的结果吗?如果您需要代码方面的帮助,您必须发布一个连贯的问题。
  • 如您在上面看到的(错误:预期表达式(在 NSFetchRequest 上)):。好的,这是一个编译错误,我将编辑我的问题。

标签: objective-c if-statement switch-statement


【解决方案1】:

如果你想在那里声明任何变量,你需要在case 中有一个单独的范围:

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;

}

旁注:如果LocalHall 是一个枚举值,那么您的代码在没有强制转换的情况下更具可读性:

switch (typeOfHall) {
    case LocalHall:
    // ...

【讨论】:

  • 谢谢我错过了大括号! Python 习惯..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 2015-11-05
  • 1970-01-01
  • 2015-03-01
  • 2013-09-10
相关资源
最近更新 更多