views:

214

answers:

1

I have a navController and tableViewController set up such that selecting a table row will push a detail view on the navController's stack and display detailed information about the row selected. In the detail view I use a single UILabel to display the info, and I set the value of the label's text property in viewDidLoad of the detail view controller.

The first time I select a row, the detail view comes up with the expected text. When I go back to the table view and select a different row, the detail view comes up with the same text as the first time.

I have seen some code samples where the detail view controller is released and then set to nil after being pushed on the navController's stack. If I add that to my code, the problem goes away, but I don't understand why.

Can someone explain to me what's going on here?

Thanks!

+1  A: 

-viewDidLoad is called only when the... well, when the view is loaded. That is to say, when it is created in memory, which is the first time you create the view controller. Any customizations based input data should be done in -viewWillAppear: instead, which gets called every time before you push it onto the navigation controller.

Although, in general practice, I always release a new view controller immediately after pushing it onto the stack, since it doesn't belong to me any more, it belongs to the navigation controller. In this case, the next time you push it on to the stack, it will load the view again, since it's a new object.

- (void) tableView:(TableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIViewController *screen = [[MyNewViewController alloc] initWithData:[data objectAtIndex:indexPath.row]];
    [self.navigationController pushViewController:screen animated:YES];
    [screen release];
}

The main idea, though, is that customizing a view based on data that may change every time you see the view should be done within -viewWillAppear:. Customizing a view further than you can in Interface Builder, changing things which won't change no matter what data you're looking at, should be done in -viewDidLoad

Ed Marty
Ed, Thanks much. That makes perfect sense and my code is now both working AND I understand why!
skantner