What is a "delegate" in Objective C's iPhone development?
A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program. The delegating object is often a responder object—that is, an object inheriting from NSResponder in AppKit or UIResponder in UIKit—that is responding to a user event.
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.
A data source is almost identical to a delegate. The difference is in the relationship with the delegating object. Instead of being delegated control of the user interface, a data source is delegated control of data.
The Delegate Pattern in Swift In Swift, a delegate is a controller object with a defined interface that can be used to control or modify the behavior of another object. One example is the UIApplicaitonDelegate in an iOS app.
A delegate is a pointer to an object with a set of methods the delegate-holder knows how to call. In other words, it's a mechanism to enable specific callbacks from a later-created object.
A good example is UIAlertView
. You create a UIAlertView
object to show a short message box to users, possibly giving them a choice with two buttons like "OK" and "Cancel". The UIAlertView
needs a way to call you back, but it has no information of which object to call back and what method to call.
To solve this problem, you can send your self
pointer to UIAlertView
as a delegate object, and in exchange you agree (by declaring the UIAlertViewDelegate
in your object's header file) to implement some methods that UIAlertView
can call, such as alertView:clickedButtonAtIndex:
.
Check out this post for a quick high-level intro to the delegate design pattern and other callback techniques.
References:
See this discussion
A delegate allows one object to send messages to another object when an event happens. For example, if you're downloading data from a web site asynchronously using the NSURLConnection class. NSURLConnection has three common delegates:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error - (void)connectionDidFinishLoading:(NSURLConnection *)connection - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
One or more of these delegates will get called when NSURLConnection encounters a failure, finishes successfully, or received a response from the web site, respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With