Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Given:</p> <pre><code>- (void)setPlanetName:(NSString *)value { if (planetName != value) { [planetName release]; planetName = [value copy]; } } </code></pre> <p>The <code>-copy</code> ensures that if someone passes in an instance of <code>NSMutableString</code> as <code>value</code>, then <code>planetName</code> won't change in your instances out from under you.</p> <p>A good defensive programming pattern. Note that <code>-copy</code> is free on immutable strings; <code>-copy</code> just bumps the retain value and returns self (the instance of the string that was copied).</p> <p>Now, consider your second example:</p> <pre><code>- (void)setPlanetName:(NSString *)value { if (planetName != value) { [planetName release]; planetName = [value retain]; } } </code></pre> <p>Perfectly valid and works fine, just not as defensive.</p> <p><strong>In both cases, <code>planetName</code> must be released in your <code>-dealloc</code> method</strong>.</p> <pre><code>- (void) dealloc { [planetName release]; planetName = nil; // defensive [super dealloc]; } </code></pre> <p>It doesn't matter if the string is copied, retained, or was originally a constant string that was passed into your setter. If you retain it (or implied retain it through copy), you must release it.</p> <p>Note that you can think of this as "escape patterns". Whenever the existing value of planetName escapes your object, you must release it. That can happen when the object is deallocated or when a new value of planetName is set, hence the -release in the setters.</p> <p>Or, if on Mac OS X, you could turn on garbage collection and be done with it. In any case, you should be using @property &amp; @synthesize to automatically generate the getter/setter pair.</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