/usr/share/GNUstep/Documentation/Developer/Base/ProgrammingManual/gs-base/Advanced-Messaging.html is in gnustep-base-doc 1.24.7-1build2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Created by GNU Texinfo 6.1, http://www.gnu.org/software/texinfo/ -->
<head>
<title>Objective-C GNUstep Base Programming Manual: Advanced Messaging</title>
<meta name="description" content="Objective-C GNUstep Base Programming Manual: Advanced Messaging">
<meta name="keywords" content="Objective-C GNUstep Base Programming Manual: Advanced Messaging">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Make.html#Make" rel="index" title="Make">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="index.html#Top" rel="up" title="Top">
<link href="Exception-Handling.html#Exception-Handling" rel="next" title="Exception Handling">
<link href="Classes.html#Classes" rel="prev" title="Classes">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.indentedblock {margin-right: 0em}
blockquote.smallindentedblock {margin-right: 0em; font-size: smaller}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smalllisp {margin-left: 3.2em}
kbd {font-style: oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nolinebreak {white-space: nowrap}
span.roman {font-family: initial; font-weight: normal}
span.sansserif {font-family: sans-serif; font-weight: normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en">
<a name="Advanced-Messaging"></a>
<div class="header">
<p>
Next: <a href="Exception-Handling.html#Exception-Handling" accesskey="n" rel="next">Exception Handling</a>, Previous: <a href="Classes.html#Classes" accesskey="p" rel="prev">Classes</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Make.html#Make" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="Advanced-Messaging-1"></a>
<h2 class="chapter">5 Advanced Messaging</h2>
<a name="index-advanced-messaging"></a>
<a name="index-messaging_002c-advanced-techniques"></a>
<p>Objective-C provides some additional possibilities for message routing besides
the capabilities described so far (inheritance and categories). One of the
most important is that it is possible for an object, upon receiving a message
it has not been set up to respond to, to <i>forward</i> that message to another
object. A second important capability, which forwarding relies on, is the
ability to represent method implementations directly in code. This supports
various reflective operations as well as optimization where messages are sent
many times.
</p>
<a name="How-Messaging-Works"></a>
<h3 class="section">5.1 How Messaging Works</h3>
<p>Sending an Objective-C message requires three types of information:
</p>
<ul>
<li> The message <b>receiver</b> - the object which is to perform the request.
</li><li> The message <b>selector</b> - this identifies the message, and is used to
locate the excecutable code of the corresponding <b>method</b> by searching the
structure of the class, and if necessary its superclasses, for an
implementation.
</li><li> The message <b>arguments</b> - once the implementation has been found, these are
simply passed to the method on the stack as in an ordinary function call.
</li></ul>
<p>In the message ’<code>[taskArray insertObject: anObj atIndex: i]</code>’, the
receiver is “<code>taskArray</code>”, the selector is
“<code>insertObject:atIndex:</code>”, and the arguments are “<code>anObj</code>” and
“<code>i</code>”. Notice that the selector includes the argument titles and both
colons, but not the argument names. In other words, this method might have
been declared as ’<code>- (void) insertObject: (id)anObject atIndex:
(unsigned)index;</code>’, but the “<code>anObject</code>” and “<code>index</code>” are just
used for tracking the arguments within the method implementation code and not
for looking up the method itself.
</p>
<p>The following sequence of events would occur on sending this message at
runtime:
</p>
<ol>
<li> The internal <code>isa</code> pointer of the <b>receiver</b> (<code>taskArray</code>) is used
to look up its class.
</li><li> The class representation is searched for a method implementation matching the
<b>selector</b> (<code>insertObject:atIndex:</code>). If it is not found, the class’s
superclass is searched, and recursively its superclass, until an
implementation is found.
</li><li> The implementation is called, as if it were a C function, using the
<b>arguments</b> given (<code>anObj</code> and <code>i</code>), and the result is returned to
the code sending the message.
</li></ol>
<p>In fact, when the method implementation is actually called, it additionally
receives two <i>implicit</i> arguments: the <b>receiver</b> and the <b>selector</b>.
These additional hidden arguments may be referred to in the source code by the
names <code>self</code> and <code>_cmd</code>.
</p>
<p>The process of looking up the method implementation in the receiver at runtime
is known as dynamic binding. This is part of what makes the language powerful
and flexible, but it is inevitably (despite clever caching strategies used in
the runtime library) a little slower than a simple function call in C. There
are, however, ways of short-circuiting the process in cases where performance
is at a premium. Before discussing this, we must first cover the concepts of
selectors and implementations in greater detail.
</p>
<a name="Selectors"></a>
<h3 class="section">5.2 Selectors</h3>
<p>So far we have been using the following syntax to send messages to objects:
</p>
<div class="example">
<pre class="example">[myArray removeObjectIdenticalTo: anObject];
</pre></div>
<p>The example sends the message named <code>removeObjectIdenticalTo:</code> to
<code>myArray</code> with the argument <code>anObject</code>.
</p>
<p>An alternative method of writing this is the following:
</p>
<div class="example">
<pre class="example">SEL removalSelector = @selector(removeObjectIdenticalTo:);
[myArray performSelector: removalSelector withObject: anObject];
</pre></div>
<p>Here, the first line obtains the desired method selector in the form of a
compiled representation (not the full ASCII name), and the second line sends
the message as before, but now in an explicit form. Since the message that is
sent is now effectively a variable set at runtime, this makes it possible to
support more flexible runtime functioning.
</p>
<a name="The-Target_002dAction-Paradigm"></a>
<h4 class="subsection">5.2.1 The Target-Action Paradigm</h4>
<p>One conventional way of using selectors is called the <i>target-action</i>
paradigm, and provides a means for, among other things, binding elements of a
graphical user interface together at runtime.
</p>
<p>The idea is that a given object may serve as a flexible signal sender if it
is given a receiver (the <i>target</i>) and a selector (the <i>action</i>) at
runtime. When the object is told to send the signal, it sends the selector
to the receiver. In some variations, the object passes itself as an
argument.
</p>
<p>The code to implement this paradigm is simple -
</p><div class="example">
<pre class="example">- (id) performAction
{
if (target == nil || action == 0)
{
return nil; // Target or action not set ... do nothing
}
if ([target respondsToSelector: action] == NO)
{
return nil; // Target cannot deal with action ... do nothing
}
return [target performSelector: action withObject: self];
}
</pre></div>
<p>As an example, consider a graphical button widget that you wish to execute
some method in your application when pressed.
</p>
<div class="example">
<pre class="example"> [button setTarget: bigMachine]
[button setAction: @selector(startUp:)];
</pre></div>
<p>Here, <code>button</code> stores the given target and action in instance variables,
then when it is pressed, it internally calls a method like
<code>performAction</code> shown above, and sends the message “<code>[bigMachine
startUp: button]</code>”.
</p>
<p>If you are used to programming with events and listeners in Java, the
target-action paradigm provides a lighter-weight alternative for the most
common case where only one object needs to be informed when an event occurs.
Rather than writing or extending a special-purpose adaptor class, you just
register the method you want called directly with the actuating element. If
you need to send the event to multiple objects, however, you would need to
write a special method to multiplex the event out. This would be
approximately comparable effort to what is always required in Java, and is
only needed in the minority of cases.
</p>
<a name="Obtaining-Selectors"></a>
<h4 class="subsection">5.2.2 Obtaining Selectors</h4>
<p>In addition to using the compile-time <code>@selector</code> operator, there are a
couple of other ways of obtaining selectors.
</p>
<ul>
<li> In a method implementation, you can always obtain the current selector from
the variable <code>_cmd</code>:
<div class="example">
<pre class="example">- (void) removeObjectIdenticalTo: (id)anObject
{
SEL mySelector = _cmd;
// ...
}
</pre></div>
</li><li> At any point, you can use the <code>NSSelectorFromString()</code> function -
<div class="example">
<pre class="example"> SEL mySelector = NSSelectorFromString(@"removeObjectIdenticalTo:");
</pre></div>
<p>In reality, you would never use <code>NSSelectorFromString</code> for a constant
string as shown; <code>@selector</code> would do and is more efficient, since is a
compile-time operator. Its chief utility lies in the case where the selector
name is in a variable value (for whatever reason).
</p>
</li></ul>
<p>If you ever need to test the contents of a <code>SEL</code> variable for equality
with another, you should use the function <code>sel_eq()</code> provided as part of
the GNU Objective-C runtime library. This is necessary because, while the
compiler tries to ensure that compile-time generated references to selectors
for a particular message point to the same structure, selectors produced at
runtime, or in different compilation units, will be different and a simple
pointer equality test will not do.
</p>
<a name="Avoiding-Messaging-Errors-when-an-Implementation-is-Not-Found"></a>
<h4 class="subsection">5.2.3 Avoiding Messaging Errors when an Implementation is Not Found</h4>
<p>Using <b>typed</b> objects as shown below, the compiler would forewarn
you if the <code>anObject</code> was unable to respond to the <code>alert:</code>
message, as it knows what type of object <code>anObject</code> is:
</p>
<div class="example">
<pre class="example">SomeClass *anObject; // an instance of the 'SomeClass' class
anObject = [[SomeClass alloc] init]; // build and initialize the object
[anObject alert: additionalObject]; // compiler warns if 'alert:' not
// defined in SomeClass or a superclass
</pre></div>
<p>However at times the compiler will not forewarn you that a message will
attempt to invoke a method that is not in the <b>receiver’s</b> repertoire. For
instance, consider the code below where <code>anObject</code> is not known to
implement the <code>alert:</code> message:
</p>
<div class="example">
<pre class="example"> id anObject; // arbitrary object;
anObject = [[SomeClass alloc] init]; // build and initialize object
[anObject alert: additionalObject]; // compiler cannot check whether
// 'alert' is defined
</pre></div>
<p>In this case, the compiler will not issue a warning, because it only knows
that <code>anObject</code> is of type <code>id</code> … so it doesn’t know what
methods the object implements.
</p>
<p>At runtime, if the Objective-C runtime library fails to find a <b>method
implementation</b> for the <code>alert:</code> message in the <code>SomeClass</code> class
or one of its superclasses, an exception is generated. This can be avoided
in one of two ways.
</p>
<p>The first way is to check in advance whether the method is implemented:
</p>
<div class="example">
<pre class="example">if ([anObject respondsToSelector: @selector(alert:)] == YES)
{
[anObject alert: additionalObject]; // send it a message.
}
else
{
// Do something else if the object can't be alerted
}
</pre></div>
<p>The second way is for the object the message was sent to to <i>forward</i> it
somewhere else.
</p>
<a name="Forwarding"></a>
<h3 class="section">5.3 Forwarding</h3>
<a name="index-forwarding"></a>
<p>What actually happens when the GNU Objective-C runtime is unable to find a
method implementation associated with an object for a given selector is that
the runtime instead sends a special <code>forwardInvocation:</code> message to the
object. (Other Objective-C runtimes do the same, but with a slightly
different message name and structure.) The object is then able to use the
information provided to handle the message in some way, a common mechanism
being to forward the message to another object known as a <b>delegate</b>, so
that the other object can deal with it.
</p>
<div class="example">
<pre class="example">- (void) forwardInvocation: (NSInvocation*)invocation
{
if ([forwardee respondsToSelector: [invocation selector]])
return [invocation invokeWithTarget: forwardee];
else
return [self doesNotRecognizeSelector: [invocation selector]];
}
</pre></div>
<ul>
<li> <b><code>invocation</code></b> is an instance of the special <code>NSInvocation</code> class
containing all the information about the original message sent, including its
<b>selector</b> and its arguments.
</li><li> <b><code>forwardee</code></b> is an instance variable containing the <code>id</code> of an
object which has been determined to be likely to implement methods that this
object does not.
</li><li> The <b><code>NSInvocation</code></b> class has a convenience method that will pass the
message on to a target object given as argument.
</li><li> The <b><code>doesNotRecognizeSelector</code></b> method is a fallback which is
implemented in <code>NSObject</code>. Unless it has been overidden, its behavior
is to raise a runtime exception (a <code>NSInvalidArgumentException</code> to be
exact), which generates an error message and aborts.
</li></ul>
<p>Forwarding is a powerful method for creating software patterns. One of these
is that forwarding can be used to in effect provide a form of multiple
inheritance. Note, however that, unlike inheritance, a forwarded method will
not show up in tests like <code>respondsToSelector</code> and
<code>isKindOfClass:</code>. This is because these methods search the inheritance
path, but ignore the forwarding path. (It is possible to override them
though.)
</p>
<p>Another pattern you may come across is <i>surrogate object</i>: surrogates
forward messages to other objects that can be assumed to be more complex. The
<code>forwardInvocation:</code> method of the surrogate object receives a message
that is to be forwarded; it determines whether or not the receiver exists, and
if it does not, then it will attempt to create it. A <b>proxy</b> object is a
common example of a surrogate object. A proxy object is useful in a remote
invocation context, as well as certain scenarios where you want one object to
fulfill functions of another.
</p>
<a name="Implementations"></a>
<h3 class="section">5.4 Implementations</h3>
<p>Recall that when a message is sent, the runtime system searches for a method
implementation associated with the recipient object for the specified
selector. (Behind the scenes this is carried out by a function
“<code>objc_msgSend()</code>”.) This may necessitate searches across multiple
superclass objects traversing upwards in the inheritance hierarchy, and takes
time. Once the runtime finds an implementation for a class, it will cache the
information, saving time on future calls. However, even just checking and
accessing the cache has a cost associated with it. In performance-critical
situations, you can avoid this by holding on to an implementation yourself.
In essence, implementations are function pointers, and the compiler provides a
datatype for storing them when found at runtime:
</p>
<div class="example">
<pre class="example">SEL getObjSelector = @selector(getObjectAtIndex:);
// get the 'getObjectAtIndex' implementation for NSArray 'taskArray'
IMP getObjImp = [taskArray methodForSelector: getObjSelector];
// call the implementation as a function
id obj = (getObjImp)( taskArray, getObjSelector, i );
</pre></div>
<p>Here, we ask the runtime system to find the ’<code>taskArray</code>’ object’s
implementation of ’<code>getObjectAtIndex</code>’. The runtime system will use the
same algorithm as if you were performing a method call to look up this code,
and then returns a function pointer to it. In the next line, this pointer is
used to call the function in the usual C fashion. Notice that the signature
includes both the object and the selector – recall that these are the two
implicit arguments, <code>self</code> and <code>_cmd</code>, that every method
implementation receives. The actual type definition for <code>IMP</code> allows
for a variable number of additional arguments, which are the explicit
arguments to the method call:
</p>
<div class="example">
<pre class="example">typedef id (*IMP)(id, SEL, ...);
</pre></div>
<p>The return type of <code>IMP</code> is <code>id</code>. However, not all methods return
<code>id</code>; for these others you can still get the implementation, but you
cannot use an <code>IMP</code> variable and instead must cast it yourself. For
example, here is such a cast for a method taking a double and returning
’<code>double</code>’:
</p>
<div class="example">
<pre class="example">double (*squareFunc)( id, SEL, double );
double result;
squareFunc = (double (*)( id, SEL, double ))
[mathObj methodForSelector: @selector(squareOf:)];
result = squareFunc(mathObj, @selector(squareOf:), 4);
</pre></div>
<p>You need to declare such a function pointer type for any method that returns
something besides <code>id</code> or <code>int</code>. It is not necessary to declare the
argument list (<code>double</code>) as we did above; the first line could have been
“<code>double (*squareFunc)( id, SEL, <b>...</b> )</code>” instead.
</p>
<p>An excellent exposition of the amount of time saved in using
<code>methodForSelector</code> and other details of the innards of Objective-C and
the Foundation may be found here:
<a href="http://www.mulle-kybernetik.com/artikel/Optimization/opti-3.html">http://www.mulle-kybernetik.com/artikel/Optimization/opti-3.html</a>.
</p>
<p>You should realize that it is only worth it to acquire the <code>IMP</code> if you
are going to call it a large number of times, and if the code in the method
implementation itself is not large compared with the message send overhead.
In addition, you need to be careful not to call it when it might be the wrong
function. Even when you are sure of the class of the object you are calling
it on, Objective-C is sufficiently dynamic that the correct function could
change as a program runs. For example, a new category for a class could be
loaded, so that the implementation of a method changes. Similarly, a class
could be loaded that poses as another, or one that was posing stops doing so.
In general, <code>IMPs</code> should be acquired just before they are to be used,
then dropped afterwards.
</p>
<hr>
<div class="header">
<p>
Next: <a href="Exception-Handling.html#Exception-Handling" accesskey="n" rel="next">Exception Handling</a>, Previous: <a href="Classes.html#Classes" accesskey="p" rel="prev">Classes</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Make.html#Make" title="Index" rel="index">Index</a>]</p>
</div>
</body>
</html>
|