views:

154

answers:

1

I have a tableView with a list of items. When a selection is made, a new view controller is pushed on the tableView's navigationController viewController stack.

My question is this: one of the views in the view hierarchy associated with the pushed view controller requires the fetching of data from the network before it can render it's content. This fetching is done asynchronously via [NSURLRequest requestWithURL: ...]. What is the proper way to pass the data to the view that needs it and have that view call it's overloaded drawRect method? Currently, I do this:

  • (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    [_connection release]; _connection = nil;

    [self performSelectorOnMainThread:@selector(GetDataFromCloudAndCreateView) withObject:nil waitUntilDone:NO];

}

Method GetDataFromCloudAndCreateView instantiates the view form the data. Unfortunately, nothing is being rendered. I have tried [myView setNeedsDisplay] but it has no effect.

Could someone sketch the proper way to do this? Thanks.

+1  A: 

What I've done in the past in a case like this is to create the new UIViewController in the connectionDidFinishLoading: method and then push it. Like so:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [_connection release];
    _connection = nil;

    // Code to stop a loading indicator of some kind

    UIViewController *newView = [[SomeViewController alloc] initWithData:fetchedData];
    [self.navigationController pushViewController:newView animated:YES];
}

The initWithData: method on the new controller takes care of any instance variables it needs based on the data I passed to it and then when the view loads it will draw the view based on those variables.

Hope that answers your question.

Cory Kilger
Cory,Just so I'm clear, the above code is running in you tableViewController correct? So for example in method tableView:accessoryButtonTappedForRowWithIndexPath: rather then pushing the viewController immediately you defer the pushing of the viewController until connectionDidFinishLoading: is called?
dugla
I think I've got a solution that appears robust. I took your idea of creating the views in connectionDidFinishLoading: but I've implemented connectionDidFinishLoading: in the pushed viewController. It is called from viewDidAppear: which allows the pre-existent view hierarchy to be fully established. I then simply add the subviews in a method I call - on the main thread - from connectionDidFinishLoading: This approach feels less like I'm fighting Cocoa. Thanks for the assist.
dugla