Note that there are some explanatory texts on larger screens.

plurals
  1. POObjective-C Accessor Methods and Use of Autorelease
    text
    copied!<p>I've been reading an apple document on Memory Management and am now a bit confused regarding the recommended implementation of Accessors. Apple cites 3 approaches in implementing accessors. </p> <p><strong>Technique 1</strong></p> <p>I've copied the code from the first technique which reflects: "Getter retains and autoreleases the value before returning it; setter releases the old value and retains (or copies) the new value." This first technique is stated to be more robust but suffers performance penalties on frequently called getters.</p> <pre><code>- (NSString*) title { return [[title retain] autorelease]; } - (void) setTitle: (NSString*) newTitle { if (title != newTitle) { [title release]; title = [newTitle retain]; // Or copy, depending on your needs. } } </code></pre> <p><em>skipping Technique 2</em></p> <p><strong>Technique 3</strong></p> <p>The third technique is better for frequently called setters and getters. This is also the method I've always followed.</p> <pre><code>- (NSString*) title { return title; } - (void) setTitle: (NSString*) newTitle { if (newTitle != title) { [title release]; title = [newTitle retain]; // Or copy, depending on your needs. } } </code></pre> <p><strong>My questions are:</strong></p> <ol> <li><p>(Technique 1) The setter first releases the existing value even if it doesn't point to anything. This would send a message to nil which I understand is supported in Objective-C but still looks odd. Am I understanding this correctly?</p></li> <li><p>(Technique 1) Why is the retain stacked inside an autorelease?</p></li> <li><p>(Technique 1) Is the caller whom uses the getter expected to call release after they're done with the object?</p></li> </ol> <p>The apple developer documentation page can be found at: <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAccessorMethods.html" rel="nofollow">Memory Management Programming Guide - Accessor Methods</a></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