Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><em>The most important thing to take away here</em>: The assignment operator <code>=</code> never mutates (i.e. changes) an object. Mutating an object can only be accomplished by sending it messages (e.g., sending <code>appendString:</code> to an <code>NSMutableString</code>). The assignment operator simply causes a pointer to point to a different object than it did before.</p> <p>Thus, it is incorrect to say:</p> <pre><code>(1) NSString * test = [[NSString alloc] init]; (2) test = @"msg"; </code></pre> <p>Line (1) creates an NSString object, and assigns <code>test</code> to point to it. Line (2) does the same thing: it creates a new, unrelated NSString object, and assigns <code>test</code> to point to it. Now the original NSString created by line (1) has nothing pointing to it, and is leaked.</p> <p>Also, you never need to <code>alloc</code> a string literal; the compiler does this implicitely when you use the <code>@"..."</code> syntax. In general, you will very rarely have to use <code>[NSString alloc]</code> at all (only when you want to use the various <code>init*</code> methods, such as <code>initWithFormat:</code>, etc.)</p> <ol> <li><code>str1</code> will point to a distinct copy of the test string. (Errata: According to Eiko, the receiver will simply treat this as a 'retain' if it is immutable. This makes no practical difference if you are behaving correctly.)</li> <li><code>str2</code> will point to the same location as test, and the retain count of the object there will be incremented.</li> <li><code>str3</code> will point to the same location as test, but the retain count will not be incremented.</li> </ol> <p>Generally speaking, strings are immutable, so you cannot change their content. You may have to watch out for instances of NSMutableString, however, which is a subclass of NSString. This is why many people recommend copying strings instead of retaining them, so that, should the string be mutated by another part of the program, your object's copy will be unaffected.</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