这个类是UITabBarViewController的子类。在我的init父视图控制器文件中,我有以下内容:
UIBarButtonItem *button1 = [[UIBarButtonItem alloc]
initWithTitle:@"Button1"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(button1:)];
self.navigationItem.rightBarButtonItem = button1;
[button1 release];所述方法:
-(IBAction)button1:(id)sender {
if (self.nvc == nil) {
ChildViewController *vc = [[ChildViewController alloc] init];
self.nvc = vc;
[vc release];
}
[self presentModalViewController:self.nvc animated:YES];我想从我的子视图控制器类中的parentviewcontroller获取一个值,这个类也是一个UITabBarViewController子类。
我怎么做,我已经尝试了几个小时,但我只得到了一个零参考。
我想要获取的对象(它是父对象中的一个属性)是一个NSString。
提前感谢
发布于 2011-01-09 08:33:52
有很多方法可以做到这一点。最简单的方法是向ChildViewController添加一个指向父视图控制器的属性。你可以称它为delegate。然后,该方法将如下所示:
-(IBAction)newbuilding:(id)sender {
if (self.nvc == nil) {
ChildViewController *vc = [[ChildViewController alloc] init];
vc.delegate = self;
self.nvc = vc;
[vc release];
}
[self presentModalViewController:self.nvc animated:YES];
}然后,您可以从ChildViewController实例访问self.delegate.someProperty。
也有一些方法可以在没有显式引用的情况下获得父视图控制器(通常是self.tabBarController,self.navigationController取决于上下文),但上面的方法非常简单,易于理解,易于调试。
发布于 2011-01-09 08:32:42
最干净的方法可能是创建一个父视图控制器实现的ChildViewControllerDelegate协议。这是iOS开发中的一种常见用法。
@protocol ChildViewControllerDelegate
- (NSString *)getSomeNSString;
@end然后,您应该使ChildViewController将此委托作为实例变量,并可通过属性进行赋值
@property (nonatomic, assign) id<ChildViewControllerDelegate> delegate;现在,在ChildViewController中,您可以使用该委托来访问该委托上的方法,在本例中,该委托将是ParentViewController。这将允许您检索所需的字符串。
[delegate getSomeNSString]对于一些简单的东西,这看起来似乎有很多工作要做,但它避免了存储从ChildViewController到其父ParentViewController的反向引用时所继承的问题。
https://stackoverflow.com/questions/4636955
复制相似问题