我正在开发一个汽车应用程序。 我有一个链接到不同 View Controller 的 tabBar(CarInfoViewController 是其中之一)。
我使用以下方式将数据传递给其中一个 View Controller
CarInfoViewController *myCarInfoController = [self.tabBarController.viewControllers objectAtIndex:2];
[myCarInfoController setSearchParam:vin];
我想知道使用 objectAtIndex 直接从 TabBar 获取 View Controller 与执行以下操作有什么区别:
CarInfoViewController *myCarInfoController = [[CarInfoViewController alloc] init];
[myCarInfoController setSearchParam:vin];
两种方式都有效!我很想知道在这种情况下最佳做法是什么。
最佳答案
我怀疑两者都可以正常工作。
当然,除非您无论如何以编程方式创建 View Controller ,并且它正是您创建的 myCarInfoController
对象,稍后将其添加到选项卡栏 Controller 。
在您的第一个语句中,您会从标签栏收到一个 Controller 。这很可能是分别在 Interface Builder 或 Storyboard Editor 中创建的 Controller 。在这个 View Controller 中,您知道它是第 1 个选项卡中的那个。 3(索引编号 2)
您的第二个语句分配了一个全新的 CarInfoViewController
实例。假设之前已经创建了一个(在 IB 左右)并且作为选项卡栏 Controller 中的第三个 Controller 驻留,那么您有两个彼此不相关的同一类实例。如果您知道将任何数据传递给 myCarInfoController
(变体 2),那么在选项卡栏 Controller 实际使用的那个实例中什么也不会发生。
关于ios - 从 TabBarController 获取 ViewController 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23703215/