参考视图使用故事板的应用程序委托

问题描述:

我想创建一个使用故事板的UITableView,但我来到的东西可能很简单,但我不知道如何解决它。 首先让我指出,我知道故事板的一个局限性在于,您将不得不挖掘故事板以查找有关您所拥有的视图的信息并将其链接到应用程序代理。 我已经创建了我的可变数组和我将在应用程序委托的表中使用的信息,现在我想将该UITableView引用到应用程序委托。层次结构是这样说参考视图使用故事板的应用程序委托

  1. 首先我有根认为,一旦你点击一个按钮,它会重定向到第二视图
  2. 第二视图里面还有另外一个,一旦你按下它,它就会按钮将您重定向到UINavigationController
  3. UINavigationController包含UITableView。

因此,您可以看到在导航控件和UITableView之前有两个视图。

这里是我尝试使用的代码,但它不工作

UIViewController *viewController = (UIViewController *)self.window.rootviewController; 

// The next line refers to the second view but does not work at all 
UIViewController *secondView = [[UIViewController viewController] objectAtIndex:1]; 

//Then the following line is to redirect from the second view to the navigation controller 
UINavigationController *navigationController =[[secondView viewController] objectAtIndex:0]; 

//Then is the table view 
BuildingsViewController *buildingsViewController = [[navigationController viewControllers] objectAtIndex:0]; 

上面的代码不起作用。谁能帮帮我吗? 非常感谢

如果此代码位于应用程序委托中,有很多原因可能导致其无法工作。首先,你似乎将View,ViewControllers和Navigation控制器与你正在做的事情混合在一起。其次,当你试图做到这一点时,并不能保证所有的视图/视图控制器还没有被创建,或者在最终的建筑视图控制器被渲染时以他们的方式连接。

什么你可以尝试,而不是在你的BuildingsViewController(你说的是你的表视图控制器),您可以通过使用

MyAppDelegate *myAppDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate 

获取句柄到App代表一旦你有一个手柄,委托你可以简单地引用您在您的BuildingsViewController中创建的可变数组结构等。

例如在 'numberOfRowsInSection' 的方法:

MyAppDelegate *myAppDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate 
NSMutableArray *myBuildings = myAppDelegate.buildingArray; 
return [myBuildings count]; 

或者cellForRowAtIndexPath方法中:

// something like this but using your names for app delegate, building array and the accessor for the building name 
MyAppDelegate *myAppDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate 
NSMutableArray *myBuildings = myAppDelegate.buildingArray; 

cell.textLabel.text = [myBuildings objectAtIndex indexPath.row].theBuildingName; 
+0

您好,感谢您的答复。 我做了你所说的并且只为numberOfRowsInSection工作。对于cellForRowAtIndexPath有一些错误,根本不起作用 – user1015777 2012-02-26 10:50:49

+0

什么部分不起作用?关键点是演示如何通过应用程序上的单例访问器访问包含表格视图控制器中的表格模型数据的数组,以访问应用程序委托。 – gamozzii 2012-02-26 23:40:14