1

I'm working on an iPhone project where I've inherited someone else's code. I have a situation where viewController A has a UIWebView and it is set as the delegate of that UIWebView.

I also have a Class B which is set as the delegate of viewController A.

In an instance of B I want to send some javascript using stringByEvaluatingJavaScriptFromString to the UIWebView in viewController A.

What's the best way of doing it?

Marco
  • 6,692
  • 2
  • 27
  • 38
Phil John
  • 1,225
  • 1
  • 15
  • 24

1 Answers1

2

You could make viewController A a delegate of Class B so that from Class B you can call a method on viewController A where the UIWebView could then execute the desired javascript.

@protocol ClassBDelegate
- (void) executeJavascript:(NSString*)jsString;
@end

@interface ClassB : NSObject<ViewControllerADelegate>
@property (nonatomic, assign) id<ClassBDelegate> delegate;
@end

@implementation ClassB
- (void) myFunc
{
   ...
   [self.delegate executeJavascript:@"alert('Awesome!');"];
}
@end

Some things are missing above like where your instance of class B has it's delegate property assigned to viewControllerA.

You would also need something like:

@interface ClassA : UIViewController<ClassBDelegate>
...
- (void) executeJavascript:(NSString*)jsString;
@end

@implementation ClassA
...
- (void) executeJavascript:(NSString*)jsString
{
   [self.myWebView stringByEvaluatingJavaScriptFromString:jsString];
}
@end

Manipulating UIElements should be left to the view controller that owns the UIElement, so for this reason I propose using a delegate. With a reference to viewController A you could directly manipulate the UIWebView, but I'd strongly advise against this. With code like this going on, who knows what other classes are also making changes on UIElements.

Sam
  • 26,946
  • 12
  • 75
  • 101
  • That sounds good. I wasn't sure if it was good practice to have A be a delegate of B and B be a delegate of A. – Phil John Sep 08 '11 at 17:07
  • 1
    @Phil John, sometimes it's unavoidable. Note that @Sam does this correctly using `assign` (or `weak` in 5.0) references for the delegate. Otherwise you could get a retain cycle. See http://cocoawithlove.com/2009/07/rules-to-avoid-retain-cycles.html – Dan Rosenstark Sep 08 '11 at 17:58