我已經實現了這一點,但我更多地詢問我是否做得對。我一直沉浸在蘋果文檔和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。
它看起來技術上沒問題,但如果你說爲什麼你需要從其他控制器訪問根控制器。 –
謝謝,我已經做到了。 – arosolino