Ok the delegation pattern is widely used in the Cocoa framework.
The file that parses data must have a protocol, anyone wanting callbacks form this
Class must implement the methods from the protocol:
//XMLParser.h
//import statements here ..
@protocol XMLParserDelegate
- (void) parserDidFinish:(NSArray*) theParsedData; //have as many methods as you please, didFail, doingProgress etc.
@end
@interface XMLParser : NSObject {
id <XMLParserDelegate> delegate; //we don't know what type of object this will be, only that it will adhere to the XMLParserDelegate protocol.
}
@property(assign) id delegate;
//methods
@end
In the implementation of the XMLParser:
@implementation XMLParser
@synthesize delegate;
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[self.delegate parserDidFinish:dataYouCollectedArray]; //this is where it happens.
}
So in your controllers interface file you says that you will adhere to the XMLParserDelegate protocol.
//MyController.h
#import "XMLParser.h"
@interface MyController : UIViewController <XMLParserDelegate> { //this is where you "promise" to implement the methods of the protocol.
}
In the MyController.m file you now instantiate the XMLParser.
@implementation MyController
- (void) init {
XMLParser *parser = [[XMLParser alloc] init];
[parser setDelegate:self] //now the parser has a reference to this object.
[parser start];
}
- (void) parserDidFinish:(NSArray*) results {
//now you have your results in the controller, can set it as the data source of the tableView and call tableView.reloadData;
}
This is a great pattern that loosely couples the caller and responder without having them know anything other that what the protocol dictates, about each other.
If I have a view element that is confined to its own functionality, like, say, a clock.
I would have a ClockViewController and it would instantiate arm, dials, etc. They would all be linked to the clock and alert the clock controller about their actions using this pattern. This way I can use the clock arm or dial in other code as I please, as long as the object instantiating them adheres to the ClockArmDelegate protocol.
Hope it makes sense:) it is the, Im pretty sure, most used pattern in Cocoa.