wakaka
wakaka

Reputation: 553

How to use methods in a informal protocol in Objective C

I am learning to program a simple Web Browser Mac App in Objective C. I have a simple textfield as an address bar and a Webview. As such, I wish to update the address the website in the textfield whenever the page changes when I click a link.

After googling, I realise I could use a method

    didStartProvisionalLoadForFrame

in the WebFrameLoadDelegate Protocol. I then proceed to type

@interface AppDelegate : NSObject <NSApplicationDelegate,WebFrameLoadDelegate>

which resulted in an error. After further search I found out that is due to WebFrameLoadDelegate being an informal Protocol.

My question is then this: What is the syntax for using the method below specified by the informal Protocol?

- (void)webView:(WebView *)webView didFinishLoadForFrame:(WebFrame*)frame;

Upvotes: 3

Views: 660

Answers (2)

TheAmateurProgrammer
TheAmateurProgrammer

Reputation: 9392

If you're manually creating a webview, then just set your own class as the delegate as following [webview setDelegate:self]. But if you made the webview in IB instead, you can link the delegate there instead.

Once you set your class as the delegate of the webview, you can just implement that method without any extra code.

- (void)webView:(WebView *)webView didFinishLoadForFrame:(WebFrame*)frame
{
    //Do stuff here.
}

And the WebView will simply call your method whenever it finishes loading a frame.

If you want to know how this works, it all goes back to the construction of a delegate. WebView will check if delegate is nil or not. If it's not, then it will call respondsToSelector: to check if the delegate has implemented the delegate method. An informal delegate is just an old way of allowing optional protocol method, which shouldn't be used anymore as stated by @JonathanGrynspan

And if you didn't know, you don't have to explicitly declare that your class confirms to a protocol (even if it's not informal) if you connect it in IB.

By the way, if you're working on a webview, check out Apple's development guide on it. It gives you a step-by-step tutorial on creating the basics of a webview including when to change the webview's URL address.

Upvotes: 3

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43470

With an informal protocol, you implement the methods without declaring conformation to a protocol. WebFrameLoadDelegate is not a type, just the name of an NSObjectcategory.

They exist because, previously, there was no way to specify that a method in a protocol was optional (the @optional and @required keywords did not exist.) When the requisite keywords were added to Objective-C, Apple started moving to formal protocols with optional methods, which makes for better type safety and self-documenting code.

Upvotes: 4

Related Questions