Lou*_*cia 3 casting objective-c uiviewcontroller ios
查看Apple示例代码iPhoneCoreDataRecipes,我对下面的代码段有一个疑问RecipeDetailViewController.m:
case TYPE_SECTION:
nextViewController = [[TypeSelectionViewController alloc]
initWithStyle:UITableViewStyleGrouped];
((TypeSelectionViewController *)nextViewController).recipe = recipe;
break;
Run Code Online (Sandbox Code Playgroud)
在这一行中((TypeSelectionViewController *)nextViewController).recipe = recipe,我理解内括号是将视图控制器强制转换为a TypeSelectionViewController,但外括号是做什么的?
这与操作的优先级有关.
如果你看这里,你会发现点符号的优先级高于强制转换.
所以这段代码:
(TypeSelectionViewController *)nextViewController.recipe
Run Code Online (Sandbox Code Playgroud)
将由编译器转换为以下(因为点.符号只是编译器的语法糖):
(TypeSelectionViewController *)[nextViewController recipe]
Run Code Online (Sandbox Code Playgroud)
但是,我们想要将nextViewController部件转换为类型TypeSelectionViewController *,而不是[nextViewController recipe]部件.所以这是不正确的.
所以我们写这个:
((TypeSelectionViewController *)nextViewController).recipe
Run Code Online (Sandbox Code Playgroud)
编译器转换为:
[(TypeSelectionViewController *)nextViewController recipe]
Run Code Online (Sandbox Code Playgroud)
这就是我们想要的.
关于编译器与运行时行为的注释
如果您编译此错误转换的示例:
UILabel *label = [[UILabel alloc] init];
NSString *result = (UILabel *)label.text;
Run Code Online (Sandbox Code Playgroud)
您将从编译器获得这样的消息:
Warning: incompatible pointer types initializing 'NSString *' with an
expression of type 'UILabel *'
Run Code Online (Sandbox Code Playgroud)
但是,由于Objective C的弱类型,代码在运行时可以正常工作.您可以在LLVM文档中阅读有关此内容的更多信息,例如:
在运行时不检查对象指针类型之间的转换的有效性.
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |