Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>File this under C NULL pointer type stuff. </p> <p>Here is an example:</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; void test(void){ NSString *test1, *test2, *test3; test1=nil; // Note: NSString would USUALLY be aloc then init before use... [test1 isEqual:@"static object string"]; [test2 isEqual:@"static string"]; [test3 isEqual:test1]; } int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; test(); [pool drain]; return 0; } </code></pre> <p>Now place a breakpoint on <code>test1=nil</code> in xcode and run. On <em>my</em> machine, I get:</p> <pre><code>test1=(NSString *) 0x0 &lt;nil&gt; test2=(NSString *) 0x0 &lt;nil&gt; test3=(NSString *) 0x7fff84db7dd7 Invalid </code></pre> <p>If you run it, you will get <code>EXC_BAD_ACCESS</code> and termination when it tries to execute <code>[test3 isEqual:test1]</code>. You can use the nil values of test1 and (accidental?) nil value of test2 but use the random value in test3: death. </p> <p>Now change that line to <code>test1=test2=test3=nil;</code> Run it again. Works great. </p> <p>An important concept: <a href="http://cocoawithlove.com/2008/06/doing-things-in-cocoa-with.html" rel="nofollow">You can validly send a message to nil</a> in Objective-C.</p> <p>Just as in may be good practice to assign a C pointer to a safe value when not in use, <code>nil</code> is a safe value in Objective-C until it is assigned to something else. For the programmer who wrote the example -- it was probably muscle memory. Unnecessary in the particular case, but safer than a random value. </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