简体   繁体   中英

Extend a protocol implementation in objective c

I have a class Foo that inherits from UIViewController and implemented an UIWebViewDelegate . Can I inherit from Foo in a new class and extends the old webViewDidFinishLoad method? I need to execute some code and after that call the webViewDidFinishLoad from the super class.

The answer is YES - I do this myself in several places. So Foo implements a protocol, and this is stated in the interface file. You can then have a new class, Goo, that is a subclass of Foo. Since Foo has publicly stated that it implements a protocol, then Goo will be declared as implementing it too.

If that protocol has mandatory methods, when the compiler will assume that Foo implements them and thus you can override any or all methods in Goo. You can (as I do) also call '[super someMethod]' to have Foo also take actions if you want.

webViewDidFinishLoad is a delegate, you can extend another class by doing:

Foo : anotherClass

but the delegate is called within the

<UIWebViewDelegate>

hope this helps.

You can override the method after you implemented the protocol and change or extend the behavior like this:

Foo.h


Foo : UIViewController {}
- (void)customWebViewDidFinishLoad:(UIWebView *)webView;

Foo.m


- (void)webViewDidFinishLoad:(UIWebView *)theWebView {
    [self customWebViewDidFinishLoad:self.webView];
}

// Override this method in Bar.m
- (void)customWebViewDidFinishLoad:(UIWebView *)webView {
    // Default behaviour
}

Bar.h


Bar : Foo  

Bar.m


- (void)customWebViewDidFinishLoad:(UIWebView *)webView {
  [super customWebViewDidFinishLoad:webView];
  //Extend the behaviour here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM