2013-10-24 233 views
3

看爲iPhoneCoreDataRecipes蘋果示例代碼,我有一個關於從RecipeDetailViewController.m下面的代碼段的問題:雙括號是什麼意思?

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

在線路((TypeSelectionViewController *)nextViewController).recipe = recipe,我明白的是,內括號是強制轉換的視圖控制器作爲TypeSelectionViewController ,但外括號是什麼呢?

+5

運算符優先級。你想看看'nextViewController'的'.recipe'作爲'(TypeSelectionViewController *)'。您不想將'nextViewController.recipe'強制轉換爲'(TypeSelectionViewController *)'。 – nhgrif

回答

9

這是一個與操作的優先級做。

如果你看看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閱讀更多關於此,例如:

對象指針類型之間轉換的有效性。

+0

好解釋! –

+0

如果您不確定優先規則,那麼就不會有額外的負擔。他們不花任何東西。 –

+0

很好的解釋。謝謝。 –

0

這是一個演員,這是說要考慮nextViewController是TypeSelectionViewController的實例,所以你可以使用它的屬性配方

+1

這不回答這個問題。這個問題已經表明他理解演員。問題是關於外部括號。 – rmaddy

相關問題