如何在视图控制器之间传递对象

时间:2013-08-04 23:26:21

标签: ios objective-c cocoa-touch

我有一个列出运动员的桌面视图。当选择运动员时,我希望将详细视图控制器(被推入堆叠的控制器)知道关于运动员的所有属性。他/她的名字,生日,电话号码等。但我不确定如何传递这些信息。

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;
    }
}

2 个答案:

答案 0 :(得分:0)

在推送详细视图控制器之前,在其上设置一个属性,其中包含要显示的数据,如:

myDetailViewController.myModel = selectedModel;

在详细视图中,您可以使用viewWillAppear中的此数据设置视图。

答案 1 :(得分:0)

我想你会想要使用代表。以下是有关如何执行此操作的精彩教程:Link