Best Practice: When to use a delegate or not? NSXMLParserDelegate vrs NSURLConnection
I am implementing a simple Twitter Client as a learning example.
My controller implements NSXMLParserDelegate with custom implementations for a series of events/callbacks. Likewise, I implement a series of callbacks for the NSURLConnection. What I don't understand is why the former is a delegate and the latter is not. It feels like both are event handler classes and could easily both be delegates. I have read the best practices on msdn and would think that both would be implemented as delegates. What am I missing here? Does it really matter?
@interface SimpleTwitterClientViewController : UIViewController <NSXMLParserDelegate> {
// Event handlers/callbacks for NSXMLParser Delegate
- (void)parserDidStartDocument:(NSXMLParser *)parser;
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict;
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName;
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
- (void)parserDidEndDocument:(NSXMLParser *)parser;
// Event handlers/callbacks for URL Connection
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)erro开发者_C百科r;
- (void) connectionDidFinishLoading: (NSURLConnection*) connection;
}
Both are implemented as delegates. You're looking at the code and guessing what it is by the name instead of reading the Apple documentation. When you see <SomeNameHere>
, that is a protocol. The delegate conforms to it, which is why the protocol is named SomethingDelegate
. It's not called that because it's a delegate.
NSURLConnection uses an informal protocol for its delegate rather than a formal one. All this really means is that the system takes your word for it when you use an object as a delegate rather than checking for itself that you implement the relevant methods. I'm not aware of any particular reason why this is the case. It's better to use formal protocols when you implement delegate systems yourself, but it's not necessary.
Don't bother reading any documentation on MSDN. That is for C#, not Objective C. Read the documentation on Apple's developer center.
精彩评论