objective-c - 访问父 View Controller (自定义)属性

标签 objective-c iphone

我已经编写了一个 UITabBarController 子类(称为 MainViewController)并添加了一些实例变量,特别是 Venue 类型的场所。 MainViewController 的每个选项卡都需要访问 MainViewController 的 field 变量。在第一个选项卡中,一个名为 HomeViewControllerUIViewController 子类,我编写了我的 viewDidLoad 方法并尝试使用两者输出到 NSLog...

NSLog(@"%@", self.parentViewController.venue.name);

NSLog(@"%@", self.tabBarController.venue.name);

但是 XCode 给出了错误

error: request for member 'venue' in something not a structure or union

我可以从 MainViewController 中访问 venue 属性,所以已经排除了那里的错误。 iPhone 模拟器确实将 self.parentViewControllerself.tabBarController 都视为 MainViewController 的实例。这条线...

NSLog(@"%@", self.tabBarController);

输出...

2009-06-05 17:54:46.502 Venue[29729:20b] <MainViewController: 0x536600>

因为它被视为一个 MainViewController 实例,我怀疑使用转换是否有帮助。是我使用 field 副本初始化 HomeViewController 的唯一其他选择,还是我只是在使用“self.parentViewController.venue.name”做一些完全错误的事情?谢谢,罗布

最佳答案

你做的事情完全错了。 parentViewController 声明为 UIViewControllerNSLog由于多态性的奇迹,它输出它的真实类型。

UIViewController 没有 Venue 成员。您的 MainViewController 可以。事实上,类型转换它是正确的答案。确保同时导入 MainViewController.h

#import "MainViewController.h"
[...]
NSString *name = ((MainViewController *)self.parentViewController)).venue.name;

当然,还要确保 venue 声明为 MainViewController 的 @propertyname@ Venue 的属性

关于objective-c - 访问父 View Controller (自定义)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/956990/

相关文章:

iphone - 使用 NSLayoutConstraint 将大型 UIView 居中

android - 通话过程如何与蓝牙设备配合使用?

ios - 如何从我的应用程序将歌曲/音频文件保存到iPhone设备iTunes?

objective-c - 将 NSInteger 转换为 NSString

ios - UIPageViewController 不会释放最后显示的对话框

iphone - UIImageView 中具有 3 种分辨率的背景

iphone - 下载 iOS SDK 应用程序

ios - Designables : Failed to render and update auto layout status. 我正在使用 Xcode 9.3

iphone - 您可以跟踪 ASIFormDataRequest 的下载进度吗?

ios - AVQueuePlayer 仅从数组中播放一次音频