无法在iOS中将MasterVC之间的数据传递给DetailVC

时间:2014-04-25 09:53:09

标签: ios objective-c

我正试图将data(_claimReportToDetailView) viewDidLoadMasterVC)传递给DetailVC。它总是null

@interface LAMasterViewController ()
{
    NSArray *_claimReports;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _claimReports = [[LADataModelController getSingleton] getClaimReportsOrderedByAccessedDate];
    LADetailViewController *detailViewController = [[LADetailViewController alloc] init];
    detailViewController.claimReportToDetailView = (LAClaimReport *)_claimReports[0];
    NSLog(@"claim%@",detailViewController.claimReportToDetailView); // captures here properly.
}

@interface LADetailViewController : UIViewController

@property(nonatomic ) LAClaimReport *claimReportToDetailView;

@end

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"sdfdf%@", _claimReportToDetailView); // logs null always.
}

4 个答案:

答案 0 :(得分:1)

你的viewDidLoad似乎很奇怪。你有这一行:

LADetailViewController *detailViewController = [[LADetailViewController alloc]init];

但是你说视图控制器在故事板上。

我认为发生的事情是你正在创建这个VC并设置它的属性,但是故事板正在加载一个全新的VC,你没有设置它的属性。

通常,在Storyboard上将信息传递给VC的方式是prepareForSegue:方法。

答案 1 :(得分:0)

这应该可以修复您的项目。试一试

//Allocating LADetailViewController instance
LADetailViewController *detailViewController = [[LADetailViewController alloc]init];

//Connecting it the specified VC on storyboard
detailViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"yourVCID"];

//Now the connection is set, so pass the data you need
detailViewController.claimReportToDetailView = (LAClaimReport *)_claimReports[0];

//Depending on present or push you should try one of the 2 lines
[self.navigationController pushViewController:detailViewController animated:YES];
//or
[self presentViewController:detailViewController animated:YES completion:nil];

答案 2 :(得分:0)

您必须将数据传递到主视图控制器中的prepareForSeque方法中的详细信息视图控制器:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDetail"]) { //<-make shire the segue identifier match one in storyboard
        _claimReports = [[LADataModelController getSingleton] getClaimReportsOrderedByAccessedDate] ;
        LADetailViewController *vc = (LADetailViewController*)[sender destinationViewController];
        vc.claimReportToDetailView = (LAClaimReport *)_claimReports[0];
    }
}

答案 3 :(得分:0)

这种情况发生的原因是,无论何时从一个UIViewController导航到另一个UIViewController,它都会再次初始化,因此,不要在viewDidLoad中设置值,而是在执行导航并通过代码而不是segue进行导航时设置事件的值。 / p>