2012-12-10 47 views
0

我已經實現了這一點,但我更多地詢問我是否做得對。我一直沉浸在蘋果文檔和iOS編程書籍中。從那時起,我已經完全重寫了我的應用程序的可重用性和所有好東西。給予所有的子視圖控制器,無論有多少級別的深層訪問根容器

現在我有一個名爲RootController的UIViewController,它處理一個UINavigationController和一個自定義的MenuController。我決定UIViewController遏制是我的RootController的最好方法。

RootController ---> UINavigationController 
       ---> MenuController 

現在出現了一個問題,我需要在UINavigationController中的一些子UIViewControllers與主RootController進行通信。

RootController ---> UINavigationController --> UIViewController 
     ^_____________________________________________| 

我決定做的事情是擴展UIViewController與類別。

的UIViewController + RootController.h

@interface UIViewController (RootController) 

@property (nonatomic, readonly) RootController *rootController; 

@end 

的UIViewController + RootController.m

@implementation UIViewController (RootController) 

- (RootController *)rootController { 
    static RootController *rootControler; 
    if(rootControler == nil) { 
     UIViewController *vc = self; 
     while((vc = vc.parentViewController)) { 
      if([vc isMemberOfClass:[RootController class]]){ 
       rootControler = (RootController *)vc; 
       break; 
      } 
     } 
    } 
    return rootControler; 
} 

@end 

當[自rootController]通過任何的UIViewController稱爲它將通過父視圖控制器循環,直到它找到一個匹配RootController,它會返回匹配。我還將該屬性設置爲靜態,因此只能查看一次。

所以我的問題是這是我做的正確方法?我試圖做一些類似於UIViewController的navigationController方法。

我需要訪問主根控制器,所以我可以從我的應用程序中的任何視圖處理MenuController。

+0

它看起來技術上沒問題,但如果你說爲什麼你需要從其他控制器訪問根控制器。 –

+0

謝謝,我已經做到了。 – arosolino

回答

1

你的解決方案似乎是正確的,但不是那麼幹淨imho。 在類似情況下,我通常更喜歡使用AppDelegate獲得「反向」方法中的引用。

例如:

#import "AppDelegate.h" // at the top of your file 

UIViewController *vc = [[(AppDelegate *)[[UIApplication sharedApplication] delegate] window] rootViewController]: 

VC是到根視圖控制器的引用。 保重,因爲窗口的根視圖控制器可以改變(如果你改變它:-)。因此,在這種情況下,你應該改變你的aproach(例如添加一個@property到你的AppDelegate並使你的RootController設置這個屬性加載)

+0

我考慮過這種方法,但對於可重用性似乎不太好。如果它最終不是UIWIndow的rootViewController,那麼我將不得不修復每行代碼以引用其他地方。 – arosolino

+0

看看我的答案的最後兩行:-)另一種方法是給你的AppDelegate添加@property,並讓你的RootVC在加載時設置這個屬性。這是更可重用的,它只需要一個快速設置(將該屬性添加到AppDelegate) – LombaX

+0

此外,如果更改你不必修改每一行代碼引用其他地方...你可以把該行放在一個類別方法並使用[self rootController]訪問它,就像您在解決方案中那樣。所以,只有一行必須改變(在第一種情況下) – LombaX

相關問題