iOS访问parentViewController中的属性

时间:2013-02-11 00:58:47

标签: ios properties parentviewcontroller childviewcontroller

尝试访问parentViewController中的方法时,我的应用程序崩溃了。这是StoryBoard中的布局

enter image description here

MainViewController = STLMMainViewController(ParentViewController)

Scene1 = STLMTimeDateViewController(ChildViewController)

这是STLMTimeDateViewController的代码

#import "STLMTimeDateViewController.h"
#import "STLMMainViewController.h"

@interface STLMTimeDateViewController ()
@property (nonatomic, strong) STLMMainViewController *stlmMainViewController;
@end


- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"The name of the controller %@",self.navigationController.parentViewController);

    stlmMainViewController= (STLMMainViewController *) self.parentViewController;
    [stlmMainViewController locationButtonSelected]; // This is where the App crashes
    NSLog(@"TimeDateController");
}

App运行,但是当调用STLMMainViewController时,应用程序崩溃时出现以下错误:

2013-02-10 16:33:57.422 MyApp[9120:c07] The name of the controller <STLMMainViewController: 0x83850d0>
2013-02-10 16:33:57.434 MyApp[9120:c07] -[UINavigationController locationButtonSelected]: unrecognized selector sent to instance 0x8371a70

如果我删除以下行:

stlmMainViewController = (STLMMainViewController *) self.parentViewController;

然后离开

[stlmMainViewController locationButtonSelected];

App运行,没有错误,但[STLMMainViewController locationButtonSelected]中的以下方法没有被调用(我从未看到日志):

-(void)locationButtonSelected
{
    [LocationButton setSelected:YES];
    [eatDrinkbutton setSelected:NO];
    [timeCalButton setSelected:NO];
    [carButton setSelected:NO];
    [contactButton setSelected:NO];
    NSLog(@"LocationButtonSelected Method");
}

locationButtonSelected方法中的所有属性和方法本身都在STLMMainViewController的.h中声明,以供公共访问。

由于

1 个答案:

答案 0 :(得分:3)

你可以试试这个:

self.stlmMainViewController= (STLMMainViewController *)self.navigationController.parentViewController;

(编辑:实际上,正如其他人刚刚指出的那样,你可能想要使用presentViewController。)

看起来你在此之前的日志消息中已经正确使用了它。在这种情况下,您需要导航控制器的父级。

BTW,你删除这一行时没有崩溃的原因是因为你最终将locationButtonSelected发送到了nil。这不会崩溃,但它也不会做任何事情。