2011-05-26 50 views
1

我一直在從頭開始編程,在Objective C中創建一個簡單的應用程序。今天,我面臨的問題是我不得不編寫一個方法,不知道它會得到什麼類型的對象。在谷歌的幫助下,我很高興發現了一種叫做「鑄造」的東西。 :)我是否必須在每條線上演員?

我使用鑄像這樣:

- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController 
{ 
    ((SpecialViewController *)viewController).aProperty = somethingInteresting; 
    ((SpecialViewController *)viewController).anotherProperty = somethingElse; 
    ((SpecialViewController *)viewController).yetAnotherProperty = moreStuff; 
} 

我必須每一行這樣的投,或者是有辦法,我可以投「的viewController」的方法的範圍一次,使我的代碼整潔?

回答

7

你可以投你的控制器來臨時變量,並使用它(還增加了類型檢查 - 以防萬一):

- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController 
{ 
    if ([viewController isKindOfClass:[SpecialViewController class]]){ 
     SpecialViewController *special = (SpecialViewController *)viewController; 
     special.aProperty = somethingInteresting; 
     special.anotherProperty = somethingElse; 
     special.yetAnotherProperty = moreStuff; 
    } 
} 
+1

+1 - 這是乾淨的 – MByD 2011-05-26 11:44:02

+0

完美。謝謝! – 2011-05-26 12:06:12

2

如何:

- (void)aCustomViewControllerNeedsToChangeStuff:(id)viewController 
{ 
    SpecialViewController * controller = (SpecialViewController *)viewController; 
    controller.aProperty = somethingInteresting; 
    controller.anotherProperty = somethingElse; 
    controller.yetAnotherProperty = moreStuff; 
} 
+0

弗拉基米爾只是把你的帖子,但謝謝:) – 2011-05-26 12:06:42

+0

那麼他的答案只是更好。 :) – MByD 2011-05-26 12:09:44

2

使用一個變量一樣

SpecialViewController *tempController = (SpecialViewController *)viewController; 

比使用此變量來訪問值如

tempController.aProperty 
相關問題