【问题标题】:Obj-C Switch Statement Integer Variable iPhoneObj-C Switch 语句整数变量 iPhone
【发布时间】:2011-02-28 02:06:03
【问题描述】:

我正在尝试使用 switch 语句来读出在 UIActionSheet 中单击了哪个按钮(为 iPhone 编程)。

以下是在我的 FirstViewController.m 中:

    - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int countarray=[areaselectArray count]; 
    switch (buttonIndex) {
        case countarray: //cancel button has been pressed
            //do stuff
            break;
        default:
            area = [areaselectArray objectAtIndex:(buttonIndex)];
            [[NSUserDefaults standardUserDefaults] setObject:area forKey:@"mulValue"];
            [areaselectArray release];
            NSLog(@"Released areaselectArray");
            break;
    }
}

UIActionSheet 的按钮是从我之前构建的(尚未发布)的数组构建的。我使用

将我的取消按钮放在列表的末尾
int countarray=[areaselectArray count];    
[areaselect.cancelButtonIndex = countarray;]

之前在分配我的 UIActionSheet 时。由于按钮的数量根据数组中的条目数量而变化,我希望“取消”按钮简单地关闭 UIActionSheet,但在所有其他情况下,让 Switch 语句将单击按钮的值写入“mulValue” " 在标准用户默认值中。

有没有办法做到这一点?当然,我现在的主要问题是 switch 函数不会使用变量(例如我的示例中的 countarray )。在进入 switch 语句之前,有什么方法可以将值写入常量(?)?

提前致谢!

【问题讨论】:

    标签: iphone objective-c switch-statement uiactionsheet


    【解决方案1】:

    为什么不使用 if 语句而不是 switch 语句?您可以使用 cancelButtonIndex 属性来检测按下取消按钮。

    if (buttonIndex == actionSheet.cancelButtonIndex) {
        // cancel button has been pressed
        // do stuff
    }
    

    此外,您还可以使用标题字符串来比较按钮。但是,按钮标题可能已本地化。小心点。

    NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([buttonTitle isEqualToString:@"Cancel"]) {
        // cancel button has been pressed
        // do stuff
    } else {
        //
    }
    

    【讨论】:

    • 好吧,简单又是规则,不是吗?这解决了它!感谢您的回答!
    【解决方案2】:

    正如您所发现的,只有常量可以跟在“大小写”之后。在 switch 语句中将与变量进行比较的值必须在编译时知道。

    要获得所需的功能,请使用 if/else 构造。就那么简单。 ;)

    编辑:

    而且,,这将编译(由于我之前提到的):

    int n = 4;
    const int a = someVariable;
    switch (n) {
        case a:
            printf("hi");
            break;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-14
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      相关资源
      最近更新 更多