What do we mean by an Object "sending messages" and how do protocols help an object to advertise the messages it supports? Does anyone have an example?
views:
54answers:
2Read the Messaging section in Apple's Objective-C Runtime Programming Guide.
It's helpful to think of objects as not merely inanimate objects, but as actors—participants that have knowledge (state), have relationships (to other objects), make decisions, and perform actions (with, to, and upon other objects).
Within this concept, instead of saying “x calls the foo
method on y”, which is a very programming-y thing to say, we talk of the objects as talking to each other. We might say “x sends a foo
message to y”, or, more specifically, “the text field x tells y that its textFieldDidChange:
” or “x asks y what its framistanCalibrationLevel
is” or any similar statement that might just as easily be about people as about imaginary objects.
(The reason for the “message” terminology is not entirely conceptual: It's brought over from Smalltalk, one of Objective-C's parent languages. That's the historical reason.)
Protocols are sort of job descriptions. Just as a person may wear the title of Janitor, or Engineer, or Director, or Receptionist, objects that fulfilled those functions might conform to protocols by those names, declaring that those objects respond to messages telling them to do, or asking them about, certain aspects of their job.
In actual Cocoa and Cocoa Touch usage, protocols typically describe a set of functions (again, not in the programming sense) that an object might provide to another object, such as a data source responding to messages by which the view can obtain the data, or a set of notifications that the object might respond to, such as an application delegate's applicationDidFinishLaunching:
, applicationWillTerminate:
, etc.
Sometimes a protocol can be even more general, like a broader version of a superclass—a real-world analogy being the many different kinds of Salesperson, and a Cocoa example being the many different classes of UI object that respond to validation messages. In some frameworks, you might make an abstract class for this, but protocols let you do the same thing (declare that a bunch of similar but different objects have some properties/abilities in common) without having to write dummy implementations.