Can I declare variables inside an Objective-C switch statement?(我可以在 Objective-C switch 语句中声明变量吗?)
问题描述
我想我要瞎了,因为我不知道这段代码中的语法错误在哪里:
I think I'm going blind, because I can't figure out where the syntax error is in this code:
if( cell == nil ) {
titledCell = [ [ [ TitledCell alloc ] initWithFrame:CGRectZero
reuseIdentifier:CellIdentifier ] autorelease
];
switch( cellNumber ) {
case 1:
NSString *viewDataKey = @"Name";
etc...
当我尝试编译它时,我得到一个 Error: syntax error before '*' token 在最后一行.
When I try to compile it, I'm getting an Error: syntax error before '*' token on the last line.
很抱歉问了这么一个基本问题,但我错过了什么?
Sorry for such a basic question, but what am I missing?
推荐答案
我手头没有合适的 Objective-C 编译器,但只要 C 结构相同即可:
I don't have a suitable Objective-C compiler on hand, but as long as the C constructs are identical:
switch { ... }
为您提供 一个 块级范围,而不是每个 case
一个.在作用域开头以外的任何地方声明变量都是非法的,并且在 switch
内部是特别危险的,因为它的初始化可能会被跳过.
switch { … }
gives you one block-level scope, not one for each case
. Declaring a variable anywhere other than the beginning of the scope is illegal, and inside a switch
is especially dangerous because its initialization may be jumped over.
以下任一方法能否解决问题?
Do either of the following resolve the issue?
NSString *viewDataKey;
switch (cellNumber) {
case 1:
viewDataKey = @"Name";
…
}
switch (cellNumber) {
case 1: {
NSString *viewDataKey = @"Name";
…
}
…
}
这篇关于我可以在 Objective-C switch 语句中声明变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以在 Objective-C switch 语句中声明变量吗?


基础教程推荐
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01