Want to create delegates in Objective-C? An Objective-C delegate is an object that has been assigned to the delegate property another object. To create one, you define a class that implements the delegate methods you’re interested in, and mark that class as implementing the delegate protocol.
For example, suppose you have a UIWebView. If you’d like to implement its delegate’s webViewDidStartLoad: method, you could create a class like this:
1 2 3 4 5 6 7 8 9 | @interface MyClass<UIWebViewDelegate> // ... @end @implementation MyClass - (void)webViewDidStartLoad:(UIWebView *)webView { // ... } @end |
Then you could create an instance of MyClass and assign it as the web view’s delegate:
1 2 | MyClass *instanceOfMyClass = [[MyClass alloc] init]; myWebView.delegate = instanceOfMyClass; |
On the UIWebView side, it probably has code similar to this to see if the delegate responds to the webViewDidStartLoad: message using respondsToSelector: and send it if appropriate.
1 2 3 | if([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { [self.delegate webViewDidStartLoad:self]; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.