双括号是什么意思?

时间:2013-10-24 14:53:48

标签: ios objective-c uiviewcontroller casting

查看iPhoneCoreDataRecipes的Apple示例代码,我对RecipeDetailViewController.m下面的代码段有疑问:

case TYPE_SECTION:
    nextViewController = [[TypeSelectionViewController alloc]
        initWithStyle:UITableViewStyleGrouped];
    ((TypeSelectionViewController *)nextViewController).recipe = recipe;
    break;

在第((TypeSelectionViewController *)nextViewController).recipe = recipe行中,我理解内括号是将视图控制器强制转换为TypeSelectionViewController,但外括号是做什么的?

2 个答案:

答案 0 :(得分:9)

这与操作的优先级有关。

如果你看here,你可以看到点符号的优先级高于强制转换。

所以这段代码:

(TypeSelectionViewController *)nextViewController.recipe

将由编译器转换为以下内容(因为dot。表示法只是编译器的语法糖):

(TypeSelectionViewController *)[nextViewController recipe]

但是,我们希望将nextViewController部分转换为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 *'

但是,由于Objective C的弱键入,代码在运行时会正常工作。您可以在LLVM docs阅读更多相关内容,例如:

  

对象指针类型之间的转换的有效性不是   在运行时检查。

答案 1 :(得分:0)

这是一个演员,据说nextViewController是TypeSelectionViewController的一个实例,所以你可以使用它的属性配方