Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>str1</code> and <code>str2</code> are <em>pointers</em> that reference the same area of memory. Your memory layout looks roughly like this: <img src="https://i.stack.imgur.com/xjmA4.png" alt="alt text"></p> <p>If you change where <code>str1</code> points, e.g., by doing this</p> <pre><code>str1 = @"new string"; </code></pre> <p>then <code>str2</code> will still reference "matrix", but <code>str1</code> will reference "new string": <img src="https://i.stack.imgur.com/MAOI3.png" alt="alt text"></p> <p>Let's say, though, that <code>str1</code> and <code>str2</code> actually pointed to an instance of an <code>NSMutableString</code>, and you did this instead:</p> <pre><code>[str2 setString:@"new string"]; </code></pre> <p>Note, then, that <code>str1</code> and <code>str2</code> would still point the same object, so by modifying <code>str2</code>, <code>str1</code> would also change to "new string".</p> <h2>Shallow copy vs. deep copy</h2> <p>A <em>shallow copy</em> is a copy of an object in which its instance variables still point to the same memory location as the original object's ivars. A <em>deep copy</em> is a copy in which copies of the instance variables are also made.</p> <p>Let's say you have a class, <code>MyClass</code>, that has two instance variables, each of type <code>NSString</code>. Here's a diagram of what the memory layout would roughly look like after a shallow and a deep copy:</p> <p><img src="https://i.stack.imgur.com/ke0RZ.png" alt="alt text"></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