Tilo Mitra
Tilo Mitra

Reputation: 2793

Calling methods on a certain UIViewController while another viewController is on the screen?

I have a regular app with a bunch of view controllers - let's say viewControllerA, viewControllerB, and viewControllerWeb.

"viewControllerWeb" is a UIWebViewDelegate and just has a UIWebView in it. I would like to call methods on it even when I am interacting with viewControllerA or viewCOntrollerB. (methods like [webview stringByEvaluatingJavaScriptFromString:])

So essentially, it seems like I want "viewControllerWeb" to be open in the background somehow. Anyone know how to accomplish something like this? Am I thinking about this the wrong way?

Hope you guys can help me out! Thanks a lot!

Upvotes: 0

Views: 403

Answers (2)

samvermette
samvermette

Reputation: 40437

Well, if you want to call these methods from the VC where the WebViewController was created, you could easily do that by making webViewController a global variable.

If you want to access it from an outside VC, then you could make WebViewController a singleton that you can access from anywhere inside your app. Something like this would do:

static WebViewController *sharedController = nil;

+ (WebViewController*)sharedController {

    if(sharedController == nil)
        sharedController = [[WebViewController alloc] initWithNibName:@"WebViewController" bundle:[NSBundle mainBundle]];

    return sharedController;
}

That would allow you to access your WebViewController from anywhere:

[[WebViewController sharedController] stringByEvaluatingJavaScript...]

EDIT: As RyanR pointed out in the comment, this obviously will keep your view controller retained until you explicitely release it. Common mistake with singletons is to forget about them and never release them — make sure you do!

Upvotes: 2

Mugunth
Mugunth

Reputation: 14499

You shouldn't be retaining a copy of your view controller. In case you want functionality to be shared, abstract it out to a singleton.

Upvotes: 1

Related Questions