Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>I was under the assumption that I can send a message to an object and it would call it whether it was there or not.</p> </blockquote> <p>You can indeed send any message to any object; that's part of the fun of Objective-C. The type of the <em>variable</em> (<code>Foo *</code>, <code>Bar *</code>, <code>id</code>, or anything else) has <em>no effect</em> on the message send. The object to which the variable points knows its class. The lookup of the corresponding method is done at runtime, via that class. The compiler turns the bracketed expression into a call to a function, <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtHowMessagingWorks.html" rel="nofollow"><code>objc_msgSend</code></a>.</p> <p>You should be getting a warning about <code>[object myString]</code> when building, saying "'Foo' may not respond to 'myString'" -- the compiler knows that there's at least one class somewhere that has a method corresponding to <code>myString</code>, and it knows that, at compile-time, <code>Foo</code> doesn't seem to be one of those, but it can't guarantee that the <code>Foo</code> won't be able to do something with the message at runtime. Messages can be resolved <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtDynamicResolution.html#//apple_ref/doc/uid/TP40008048-CH102-SW1" rel="nofollow">in custom ways during runtime</a>. Notice that if you change the type of the variable to <code>id</code>, the warning disappears -- the compiler can no longer reason about what methods are available.</p> <p>If it turns out that the object to which you send <code>myString</code> <em>doesn't</em> respond (i.e., if the object <em>really is</em> a <code>Foo</code> instead of a <code>Bar</code>, or one of <code>Foo</code>'s subclasses that doesn't implement <code>myString</code>), an exception will be raised. This is the default response (by anything that inherits from <code>NSObject</code>) to an unrecognized message.</p> <p>If you have a heterogenous collection of objects to which you need to send messages, you will probably want to test each object first. You can do as jstevenco suggested, and test for functionality:</p> <pre><code>if( [object respondsToSelector:@selector(myString)] ){ </code></pre> <p>or test for identity:</p> <pre><code>if( [object isKindOfClass:[Bar class]] ){ </code></pre> <p>The latter will pass if the object is a <code>Bar</code> or any of <code>Bar</code>'s subclasses. Use <code>isMemberOfClass:</code> to test only for the class you specify.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload