iosjsonviewdidloadsetneedsdisplay

Refresh view controller with new data after JSON request


NSString * storyboardName = @"storyboardX";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"viewControllerX"];
[vc.view setNeedsDisplay];

I am trying to refresh the display in a view controller after a JSON request completes in another thread. The data refreshes correctly, however the view does not. I am trying setNeedsDisplay at the end of the data pull method but it crashes with NSRangeException index 0 beyond bounds. I assume this is because the view controller above is not instantiated correctly, or the current view is not being deallocated. ARC is on.

I have also tried [vc.view viewDidLoad] with the same result.

The code above is located at the end of the (void)main JSON pull method.


Solution

  • 1) Your JSON pull is probably not executing in the main thread (I'm assuming this as you've not shown it, and if its not it should be anyway if the json is being obtained from a server) and GUI code can't be called on a background thread.

    2) However you should not be doing what you are attempting anyway, unless you really do want to load a view controller as opposed to refresh an existing one that is already loaded. - The code you have will create a brand new instance of the view controller, but if you already have one showing now you will have two duplicate instances of the same view controller.

    You should add a method to your view controller to redraw its contents. Then when the JSON is ready fire an NSNotification. Have your view controller listening for the notification and call your method which is doing the refreshing of the views.