Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Every object has a reference count. When it goes to 0, the object is deallocated.</p> <p>Assuming the property was declared as <code>@property (retain)</code>:</p> <p>Your first example, line by line:</p> <ol> <li>The object is created by <code>alloc</code>, it has a reference count of 1.</li> <li>The object is handed over to <code>self</code>'s <code>setAController:</code> method, which sends it a <code>retain</code> message (because the method doesn't know where the object is coming from), incrementing its reference count to 2.</li> <li>The calling code no longer needs the object itself, so it calls <code>release</code>, decrementing the reference count to 1.</li> </ol> <p>Your second example basically does steps 1 and 2 but not 3, so at the end the object's reference count is 2.</p> <p>The rule is that if you create an object, you are responsible for releasing it when you're done with it. In your example, the code is done with tempAController after it sets the property. It is the setter method's responsibility to call <code>retain</code> if it needs that object to stick around.</p> <p>It's important to remember that <code>self.property = foo;</code> in Objective-C is really just shorthand for <code>[self setProperty:foo];</code> and that the <code>setProperty:</code> method is going to be retaining or copying objects as needed.</p> <p>If the property was declared <code>@property (copy)</code>, then the object would have been copied instead of retained. In the first example, the original object would be released right away; in the second example, the original object's reference count would be 1 even though it should be 0. So you would still want to write your code the same way.</p> <p>If the property was declared <code>@property (assign)</code>, then <code>self</code> isn't claiming ownership of the object, and somebody else needs to retain it. In this case, the first example would be incorrect. These sorts of properties are rare, usually only used for object delegates.</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