看一下Apple的示例代码iPhoneCoreDataRecipes
,我对以下代码段有疑问RecipeDetailViewController.m
:
case TYPE_SECTION:
nextViewController = [[TypeSelectionViewController alloc]
initWithStyle:UITableViewStyleGrouped];
((TypeSelectionViewController *)nextViewController).recipe = recipe;
break;
在这一行中((TypeSelectionViewController *)nextViewController).recipe = recipe
,我了解到内部括号将类型转换为视图控制器TypeSelectionViewController
,但是外部括号是做什么的?
这与操作的优先级有关。
如果您在此处查看,您会发现点符号的优先级高于强制转换。
所以这段代码:
(TypeSelectionViewController *)nextViewController.recipe
将由编译器转换为以下格式(因为点号表示法只是编译器的语法糖):
(TypeSelectionViewController *)[nextViewController recipe]
但是,我们希望将nextViewController
零件转换为type TypeSelectionViewController *
,而不是[nextViewController recipe]
零件。所以这是不正确的。
因此,我们这样写:
((TypeSelectionViewController *)nextViewController).recipe
编译器将其转换为此:
[(TypeSelectionViewController *)nextViewController recipe]
这就是我们想要的。
关于编译器与运行时行为的说明
如果编译此示例不正确的转换:
UILabel *label = [[UILabel alloc] init];
NSString *result = (UILabel *)label.text;
您将从编译器收到如下消息:
Warning: incompatible pointer types initializing 'NSString *' with an
expression of type 'UILabel *'
但是,由于目标C的类型较弱,因此代码在运行时可以正常运行。您可以在LLVM文档中阅读有关此内容的更多信息,例如:
在运行时不检查对象指针类型之间转换的有效性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句