stack overflow的解释
http://stackoverflow.com/questions/2534094/what-is-a-delegate-in-objective-cs-iphone-development
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 theNSURLConnection 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.
A delegate is a pointer to an object with a set of methods the delegate-holder knows how to call. In other words, it'sa 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". TheUIAlertView
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 theUIAlertViewDelegate
in your object's header file) to implement some methods thatUIAlertView
can call, such asalertView:clickedButtonAtIndex:
.
The delegate fires the automatic events in Objects C. If you set the delegate to Object, it sends the message to another object through the delegate methods.
It's a way to modify the behavior of a class without requiring subclassing.
Each Objects having the delegate methods.These delegate methods fires, when the particular Objects take part in user interaction and Program flow cycle.
Simply stated: delegation is a way of allowing objects to interact with each other without creating strong interdependencies between them.