开关盒内的变量定义

时间:2013-11-25 17:57:04

标签: objective-c syntax switch-statement

#pragma mark AlertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];

    switch (buttonIndex) {
        case 0:
            UIWebView *webview = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024,768)];
            NSString * URLString =@"http://www.google.com";
            NSURL *URL = [NSURL URLWithString: URLString];
            NSURLRequest *request=[NSURLRequest requestWithURL:URL];
            [webview loadRequest:request]; // Use of undeclared identifier webview
            [self.view addSubview:webview]; // Use of undeclared identifier webview
            break;
        case 1:
            //if Yes button pressed on logout alert
            [self notificationAction];
            [userdefault removeObjectForKey:@"Login"];
            [userdefault synchronize];
            break;
        default:
            break;
    }
}

这是我用来显示网页的代码。但是在Xcode中我在第一个案例的第一行得到以下错误:

Expected Expression

我是否错过了我想要导入的头文件,或者我做错了什么?

1 个答案:

答案 0 :(得分:2)

在案例内的第一行定义变量时,您必须在{ }

中包装该案例的代码
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];

    switch (buttonIndex) {
        case 0:
        {
            UIWebView *webview = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024,768)];
            NSString * URLString =@"http://www.google.com";
            NSURL *URL = [NSURL URLWithString: URLString];
            NSURLRequest *request=[NSURLRequest requestWithURL:URL];
            [webview loadRequest:request]; // Use of undeclared identifier webview
            [self.view addSubview:webview]; // Use of undeclared identifier webview
            break;
        }
        case 1:
            //if Yes button pressed on logout alert
            [self notificationAction];
            [userdefault removeObjectForKey:@"Login"];
            [userdefault synchronize];
            break;
        default:
            break;
    }
}

为什么呢?显然,在switch-case中定义变量时,C的范围存在问题。将代码包装在{ }中会创建一个新的本地范围。