【问题标题】:What do the double parenthesis mean?双括号是什么意思?
【发布时间】:2013-10-24 14:53:47
【问题描述】:

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

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

((TypeSelectionViewController *)nextViewController).recipe = recipe 行中,我知道内括号是将视图控制器类型转换为TypeSelectionViewController,但是外括号是做什么的?

【问题讨论】:

  • 运算符优先级。您想将.recipenextViewController 视为(TypeSelectionViewController *)。您不想将nextViewController.recipe 转换为(TypeSelectionViewController *)

标签: ios objective-c uiviewcontroller casting


【解决方案1】:

这与操作的优先级有关。

如果您查看 here ,您会发现点表示法的优先级高于强制转换。

所以这段代码:

(TypeSelectionViewController *)nextViewController.recipe

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

(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 上阅读更多相关信息,例如:

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

【讨论】:

  • 如果您不确定优先规则,多加括号也无妨。他们不花钱。
  • 很好的解释。谢谢。
【解决方案2】:

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

【讨论】:

  • 这没有回答问题。问题已经表明他了解演员阵容。问题是关于外括号的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
  • 1970-01-01
相关资源
最近更新 更多