PDA

View Full Version : Anonymous Delegate?




jsonli
Dec 10, 2009, 10:58 PM
Cocoa heads,

I'm still learning this platform,

But I'm looking at the ASIHTTPRequest lib, and for asynchronous calls, you set the delegate to get the callbacks (error, response received, etc), but that delegate can be anything (no protocol).

I looked into the implementation of the lib, and all the callback methods are wrapped with respondsToSelector to prevent any runtime errors.

To me, this seems too loosely coupled. Is there a reason for this, and is this best practice?

Is it because there would be too many protocol methods to implement? Or... it's convenient to implement only the delegate methods of your choice? Or...?



PhoneyDeveloper
Dec 11, 2009, 12:08 AM
Protocols have optional and required methods. Sounds like this one is all optional. Sometimes it's like that. What's the problem?

jsonli
Dec 11, 2009, 12:17 AM
What I mean is there is no protocol used at all for the delegate callback methods.

I'll show you:

NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];

(http://allseeing-i.com/ASIHTTPRequest/How-to-use)

The delegate is of anonymous type id, so no protocols need to be implemented - the compiler doesn't say anything.

The delegate is free to implement as many methods as they want, and there are no runtime methods because the implementation checks with respondsToSelector if the method is implemented.

What I want to know is why they chose not to use a protocol to enforce the delegate method implementations. The way it's done now, it seems like too loosely-coupled. I can implement some (but not enough) of the methods, I can mistype the delegate methods, etc.

Generally I think that if I have the option of the compiler generating a warning when I've missed something, that's good and I should take advantage of that. This design doesn't give me that, which I'm perfectly okay with if there is a reason it, I just want to understand why.

kainjow
Dec 11, 2009, 12:26 AM
Glancing a the change log, it looks like the class wasn't originally written for the iPhone. I believe it was OS X 10.5 that introduced the @optional and @required keywords for @properties, so maybe the developer wrote it for 10.4, or shortly after 10.5 was released, or just didn't want to use a normal @protocol.

Either way, when using informal delegates a class should give run-time warnings if the delegate doesn't implement all the required methods. This is what OS X's NSTableView did (and probably still does).

jsonli
Dec 11, 2009, 12:28 AM
Ah okay, that makes sense.

Thanks.

PhoneyDeveloper
Dec 11, 2009, 12:12 PM
This is called an informal protocol. I think that all protocols were done this way in the old days on Mac OS X. If all the methods are optional there's not much difference between this and a formal protocol.