问题描述
我编写了一个 UITabBarController
子类(名为 MainViewController
)并添加了一些实例变量,特别是一个类型地点。 MainViewController
的每个选项卡都需要访问 MainViewController
的场地变量。在第一个选项卡中,一个名为 HomeViewController
的 UIViewController
子类,我写了 viewDidLoad
方法并试图用两个输出到NSLog ...
I have written a UITabBarController
subclass (called MainViewController
) and added a few instance variables, specifically a venue of type Venue. Each tab of the MainViewController
needs to access the venue variable of the MainViewController
. In the first tab, a UIViewController
subclass named HomeViewController
, I wrote my viewDidLoad
method and tried to output to NSLog with both...
NSLog(@"%@", self.parentViewController.venue.name);
和
NSLog(@"%@", self.tabBarController.venue.name);
但是XCode给出错误
But XCode gives the error
error: request for member 'venue' in something not a structure or union
我可以从 MainViewController
中访问场地属性,所以在那里排除了错误。 iPhone模拟器确实看到 self.parentViewController
和 self.tabBarController
作为 MainViewController的实例
。该行......
I can access the venue property from within MainViewController
just fine so have ruled out an error there. The iPhone simulator does see both self.parentViewController
and self.tabBarController
as an instance of MainViewController
. The line...
NSLog(@"%@", self.tabBarController);
输出......
2009-06-05 17:54:46.502 Venue[29729:20b] <MainViewController: 0x536600>
因为它被视为 MainViewController
实例,我怀疑使用铸造会有所帮助。我唯一的另一个选择是使用场地副本初始化 HomeViewController
,或者我只是做了' self.parentViewController.venue的完全错误。名称
'?谢谢,Rob
Since it's seen as a MainViewController
instance, I doubt using casting would help. Is my only other option to initialize the HomeViewController
with a copy of the venue or am I just doing something completely wrong with 'self.parentViewController.venue.name
'? Thanks, Rob
推荐答案
你做错了什么。 parentViewController
被声明为 UIViewController
。 NSLog
由于多态性的奇迹,它输出它的真实类型。
You're doing something completely wrong. parentViewController
is declared as a UIViewController
. NSLog
ing it outputs its real type due to the wonders of polymorphism.
UIViewController
没有 Venue
成员。您的 MainViewController
可以。事实上,铸造它是正确的答案。确保也导入 MainViewController.h
。
UIViewController
doesn't have a Venue
member. Your MainViewController
does. Casting it is, in fact, the right answer. Make sure to import MainViewController.h
as well.
#import "MainViewController.h"
[...]
NSString *name = ((MainViewController *)self.parentViewController)).venue.name;
当然,还要确保场地
被声明为MainViewController的 @property
, name
是 @property
Venue
。
Also make sure, of course, that venue
is declared as a @property
of MainViewController, and name
is a @property
of Venue
.
这篇关于访问父视图控制器(自定义)属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!