gpt4 book ai didi

ios 我想从 AppDelegate 访问 MainViewController 中的对象

转载 作者:行者123 更新时间:2023-11-29 04:31:02 25 4
gpt4 key购买 nike

我使用了示例项目 AppPrefs 中的这一行:

UITableView *tableView = ((UITableViewController *)self.navController.visibleViewController).tableView;

它当然可以完美地工作,

所以我尝试了:

UISearchBar *searchBar = (UIViewController *)mySearchBar;

但我收到警告,mySearchBar 未声明,即使它是一个属性并在 MainViewController(属于 UIViewController 类)中初始化。

我需要从 AppDelegate 访问 MainViewController 中的各种对象,以便应用程序可以在设置更改时自行刷新。

最佳答案

哎呀,你的代码在尽可能多的地方都是错误的。让我解释一下哪里:

一个。您将 mySearchBar 转换为 UIViewController *,然后将其分配给不同的指针类型(UISearchBar * 类型)。

两个。如果您是从应用程序委托(delegate)编写此代码,那么编译器为什么应该知道您正在使用哪个类(甚至更进一步,哪个对象的)属性?可能有多个对象/类具有相同名称的属性。

我觉得你混淆了类型转换和访问属性(所以我强烈建议在直接深入 iOS 开发之前正确学习纯 C,因为这是一个基本问题,如果你不这样做,你可能会生成低质量的代码了解这个)。您应该维护 View Controller 的实例(将其设为全局变量、单例,或者更好的是应用程序委托(delegate)对象的属性)并从那里访问它。示例:

UISearchBar *bar = [[[[UIApplication sharedApplication] delegate] mainViewController] searchBar];

关于ios 我想从 AppDelegate 访问 MainViewController 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11729129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com