how to pass objects between view controllers

て烟熏妆下的殇ゞ 提交于 2020-01-11 14:39:49

问题


I have a table view that lists athletes. when an athlete is selected, I wish to have the detail view controller (the controller that is pushed onto the stack) to know all the attributes about the athlete. his/her name, birthday, phone number, etc. But im unsure on how to pass this information.

allathletes.h

-(void)viewWillAppear:(BOOL)animated{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    _managedObjectContext = [appDelegate managedObjectContext];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *athlete = [NSEntityDescription entityForName:@"Athlete" inManagedObjectContext:_managedObjectContext];
    [request setEntity:athlete];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"last" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
    [request setSortDescriptors:sortDescriptors];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil){
        //handle error
    }
    [self setAthleteArray:mutableFetchResults];
    [self.tableView reloadData];
}


-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSString *segueIdentifier = [segue identifier];
    if ([segueIdentifier isEqualToString:@"setAthlete"])
    {
        UINavigationController *navController = (UINavigationController *)[segue destinationViewController];
        AllAthletes *athleteList = (AllAthletes *)[[navController viewControllers] lastObject];
        //the line below gets an error :(
        AthleteDetail.managedObjectContext = self.managedObjectContext;
    }
}

回答1:


Before pushing a detail view controller, set a property on it with the data to be displayed, like:

myDetailViewController.myModel = selectedModel;

In the detail view, you can set up the view using this data in viewWillAppear.




回答2:


I think you're going to want to use delegates. Here is a great tutorial on how to do that: Link



来源:https://stackoverflow.com/questions/18048633/how-to-pass-objects-between-view-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!