<p>I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's <code>malloc</code> and <code>free</code> concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet.</p>

<p>How do <code>release</code>, <code>retain</code> and <code>autorelease</code> work and what are the conventions about their use?</p>

<p>(Or failing that, what did you read which helped you get it?)</p>

[{'answer_id': 6592, 'author': 'Ecton', 'author_id': 457, 'author_profile': 'https://Stackoverflow.com/users/457', 'pm_score': 3, 'selected': False, 'text': '<p>Objective-C uses <a href="http://en.wikipedia.org/wiki/Reference_counting" rel="noreferrer">Reference Counting</a>, which means each Object has a reference count. When an object is created, it has a reference count of "1". Simply speaking, when an object is referred to (ie, stored somewhere), it gets "retained" which means its reference count is increased by one. When an object is no longer needed, it is "released" which means its reference count is decreased by one.</p>\n\n<p>When an object\'s reference count is 0, the object is freed. This is basic reference counting.</p>\n\n<p>For some languages, references are automatically increased and decreased, but objective-c is not one of those languages. Thus the programmer is responsible for retaining and releasing.</p>\n\n<p>A typical way to write a method is:</p>\n\n<pre><code>id myVar = [someObject someMessage];\n.... do something ....;\n[myVar release];\nreturn someValue;\n</code></pre>\n\n<p>The problem of needing to remember to release any acquired resources inside of code is both tedious and error-prone. Objective-C introduces another concept aimed at making this much easier: Autorelease Pools. Autorelease pools are special objects that are installed on each thread. They are a fairly simple class, if you look up NSAutoreleasePool.</p>\n\n<p>When an object gets an "autorelease" message sent to it, the object will look for any autorelease pools sitting on the stack for this current thread. It will add the object to the list as an object to send a "release" message to at some point in the future, which is generally when the pool itself is released.</p>\n\n<p>Taking the code above, you can rewrite it to be shorter and easier to read by saying:</p>\n\n<pre><code>id myVar = [[someObject someMessage] autorelease];\n... do something ...;\nreturn someValue;\n</code></pre>\n\n<p>Because the object is autoreleased, we no longer need to explicitly call "release" on it. This is because we know some autorelease pool will do it for us later.</p>\n\n<p>Hopefully this helps. The Wikipedia article is pretty good about reference counting. More information about <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Concepts/AutoreleasePools.html" rel="noreferrer">autorelease pools can be found here</a>. Also note that if you are building for Mac OS X 10.5 and later, you can tell Xcode to build with garbage collection enabled, allowing you to completely ignore retain/release/autorelease.</p>\n'}, {'answer_id': 6598, 'author': 'Matt Sheppard', 'author_id': 797, 'author_profile': 'https://Stackoverflow.com/users/797', 'pm_score': 3, 'selected': False, 'text': "<p>Joshua (#6591) - The Garbage collection stuff in Mac OS X 10.5 seems pretty cool, but isn't available for the iPhone (or if you want your app to run on pre-10.5 versions of Mac OS X).</p>\n\n<p>Also, if you're writing a library or something that might be reused, using the GC mode locks anyone using the code into also using the GC mode, so as I understand it, anyone trying to write widely reusable code tends to go for managing memory manually.</p>\n"}, {'answer_id': 6610, 'author': 'Mike McMaster', 'author_id': 544, 'author_profile': 'https://Stackoverflow.com/users/544', 'pm_score': 2, 'selected': False, 'text': '<p>NilObject\'s answer is a good start. Here\'s some supplemental info pertaining to manual memory management (<em>required on the iPhone</em>).</p>\n\n<p>If you personally <code>alloc/init</code> an object, it comes with a reference count of 1. You are responsible for cleaning up after it when it\'s no longer needed, either by calling <code>[foo release]</code> or <code>[foo autorelease]</code>. release cleans it up right away, whereas autorelease adds the object to the autorelease pool, which will automatically release it at a later time. </p>\n\n<p>autorelease is primarily for when you have a method that needs to return the object in question (<em>so you can\'t manually release it, else you\'ll be returning a nil object</em>) but you don\'t want to hold on to it, either.</p>\n\n<p>If you acquire an object where you did not call alloc/init to get it -- for example:</p>\n\n<pre><code>foo = [NSString stringWithString:@"hello"];\n</code></pre>\n\n<p>but you want to hang on to this object, you need to call [foo retain]. Otherwise, it\'s possible it will get <code>autoreleased</code> and you\'ll be holding on to a nil reference <em>(as it would in the above <code>stringWithString</code> example</em>). When you no longer need it, call <code>[foo release]</code>.</p>\n'}, {'answer_id': 6614, 'author': 'Matt Dillard', 'author_id': 863, 'author_profile': 'https://Stackoverflow.com/users/863', 'pm_score': 8, 'selected': True, 'text': '<p>Let\'s start with <code>retain</code> and <code>release</code>; <code>autorelease</code> is really just a special case once you understand the basic concepts.  </p>\n\n<p>In Cocoa, each object keeps track of how many times it is being referenced (specifically, the <code>NSObject</code> base class implements this).  By calling <code>retain</code> on an object, you are telling it that you want to up its reference count by one.  By calling <code>release</code>, you tell the object you are letting go of it, and its reference count is decremented.  If, after calling <code>release</code>, the reference count is now zero, then that object\'s memory is freed by the system.</p>\n\n<p>The basic way this differs from <code>malloc</code> and <code>free</code> is that any given object doesn\'t need to worry about other parts of the system crashing because you\'ve freed memory they were using.  Assuming everyone is playing along and retaining/releasing according to the rules, when one piece of code retains and then releases the object, any other piece of code also referencing the object will be unaffected.</p>\n\n<p>What can sometimes be confusing is knowing the circumstances under which you should call <code>retain</code> and <code>release</code>.  My general rule of thumb is that if I want to hang on to an object for some length of time (if it\'s a member variable in a class, for instance), then I need to make sure the object\'s reference count knows about me.  As described above, an object\'s reference count is incremented by calling <code>retain</code>.  By convention, it is also incremented (set to 1, really) when the object is created with an "init" method.  In either of these cases, it is my responsibility to call <code>release</code> on the object when I\'m done with it.  If I don\'t, there will be a memory leak.</p>\n\n<p>Example of object creation:</p>\n\n<pre><code>NSString* s = [[NSString alloc] init];  // Ref count is 1\n[s retain];                             // Ref count is 2 - silly\n                                        //   to do this after init\n[s release];                            // Ref count is back to 1\n[s release];                            // Ref count is 0, object is freed\n</code></pre>\n\n<p>Now for <code>autorelease</code>.  Autorelease is used as a convenient (and sometimes necessary) way to tell the system to free this object up after a little while.  From a plumbing perspective, when <code>autorelease</code> is called, the current thread\'s <code>NSAutoreleasePool</code> is alerted of the call.  The <code>NSAutoreleasePool</code> now knows that once it gets an opportunity (after the current iteration of the event loop), it can call <code>release</code> on the object.  From our perspective as programmers, it takes care of calling <code>release</code> for us, so we don\'t have to (and in fact, we shouldn\'t).</p>\n\n<p>What\'s important to note is that (again, by convention) all object creation <em>class</em> methods return an autoreleased object.  For example, in the following example, the variable "s" has a reference count of 1, but after the event loop completes, it will be destroyed.</p>\n\n<pre><code>NSString* s = [NSString stringWithString:@"Hello World"];\n</code></pre>\n\n<p>If you want to hang onto that string, you\'d need to call <code>retain</code> explicitly, and then explicitly <code>release</code> it when you\'re done.</p>\n\n<p>Consider the following (very contrived) bit of code, and you\'ll see a situation where <code>autorelease</code> is required:</p>\n\n<pre><code>- (NSString*)createHelloWorldString\n{\n    NSString* s = [[NSString alloc] initWithString:@"Hello World"];\n\n    // Now what?  We want to return s, but we\'ve upped its reference count.\n    // The caller shouldn\'t be responsible for releasing it, since we\'re the\n    // ones that created it.  If we call release, however, the reference \n    // count will hit zero and bad memory will be returned to the caller.  \n    // The answer is to call autorelease before returning the string.  By \n    // explicitly calling autorelease, we pass the responsibility for\n    // releasing the string on to the thread\'s NSAutoreleasePool, which will\n    // happen at some later time.  The consequence is that the returned string \n    // will still be valid for the caller of this function.\n    return [s autorelease];\n}\n</code></pre>\n\n<p>I realize all of this is a bit confusing - at some point, though, it will click.  Here are a few references to get you going:</p>\n\n<ul>\n<li><a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html" rel="noreferrer" title="Apple&#39;s introduction to Cocoa&#39;s memory management">Apple\'s introduction</a> to memory management.</li>\n<li><a href="https://rads.stackoverflow.com/amzn/click/com/0321774086" rel="noreferrer" rel="nofollow noreferrer">Cocoa Programming for Mac OS X (4th Edition)</a>, by Aaron Hillegas - a very well written book with lots of great examples.  It reads like a tutorial.</li>\n<li>If you\'re truly diving in, you could head to <a href="http://www.bignerdranch.com/" rel="noreferrer" title="Big Nerd Ranch">Big Nerd Ranch</a>.  This is a training facility run by Aaron Hillegas - the author of the book mentioned above.  I attended the Intro to Cocoa course there several years ago, and it was a great way to learn.</li>\n</ul>\n'}, {'answer_id': 6776, 'author': 'Ecton', 'author_id': 457, 'author_profile': 'https://Stackoverflow.com/users/457', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n<p><a href="https://stackoverflow.com/questions/6578/understanding-reference-counting-with-cocoa-objective-c#6614">Matt Dillard wrote</a>:</p>\n<p>return [[s autorelease] release];</p>\n</blockquote>\n<p>Autorelease does <em>not</em> retain the object. Autorelease simply puts it in queue to be released later. You do not want to have a release statement there.</p>\n'}, {'answer_id': 6933, 'author': 'Chris Hanson', 'author_id': 714, 'author_profile': 'https://Stackoverflow.com/users/714', 'pm_score': 3, 'selected': False, 'text': "<p>If you're writing code for the desktop and you can target Mac OS X 10.5, you should at least look into using Objective-C garbage collection.  It really will simplify most of your development — that's why Apple put all the effort into creating it in the first place, and making it perform well.</p>\n\n<p>As for the memory management rules when not using GC:</p>\n\n<ul>\n<li>If you create a new object using <code>+alloc/+allocWithZone:</code>, <code>+new</code>, <code>-copy</code> or <code>-mutableCopy</code> or if you <code>-retain</code> an object, you are taking ownership of it and must ensure it is sent <code>-release</code>.</li>\n<li>If you receive an object in any other way, you are <em>not</em> the owner of it and should <em>not</em> ensure it is sent <code>-release</code>.</li>\n<li>If you want to make sure an object is sent <code>-release</code> you can either send that yourself, or you can send the object <code>-autorelease</code> and the current <em>autorelease pool</em> will send it <code>-release</code> (once per received <code>-autorelease</code>) when the pool is drained.</li>\n</ul>\n\n<p>Typically <code>-autorelease</code> is used as a way of ensuring that objects live for the length of the current event, but are cleaned up afterwards, as there is an autorelease pool that surrounds Cocoa's event processing.  In Cocoa, it is <em>far</em> more common to return objects to a caller that are autoreleased than it is to return objets that the caller itself needs to release.</p>\n"}, {'answer_id': 8078, 'author': 'Andrew Grant', 'author_id': 1043, 'author_profile': 'https://Stackoverflow.com/users/1043', 'pm_score': 3, 'selected': False, 'text': '<p>If you understand the process of retain/release then there are two golden rules that are "duh" obvious to established Cocoa programmers, but unfortunately are rarely spelled out this clearly for newcomers.</p>\n\n<ol>\n<li><p>If a function which returns an object has <code>alloc</code>, <code>create</code> or <code>copy</code> in its name then the object is yours. You must call <code>[object release]</code> when you are finished with it. Or <code>CFRelease(object)</code>, if it\'s a Core-Foundation object.</p></li>\n<li><p>If it does NOT have one of these words in its name then the object belongs to someone else. You must call <code>[object retain]</code> if you wish to keep the object after the end of your function.</p></li>\n</ol>\n\n<p>You would be well served to also follow this convention in functions you create yourself.</p>\n\n<p>(Nitpickers: Yes, there are unfortunately a few API calls that are exceptions to these rules but they are rare).</p>\n'}, {'answer_id': 66772, 'author': 'charles', 'author_id': 9900, 'author_profile': 'https://Stackoverflow.com/users/9900', 'pm_score': 1, 'selected': False, 'text': '<p>Lots of good information on cocoadev too:</p>\n\n<ul>\n<li><a href="http://www.cocoadev.com/index.pl?MemoryManagement" rel="nofollow noreferrer">MemoryManagement</a></li>\n<li><a href="http://www.cocoadev.com/index.pl?RulesOfThumb" rel="nofollow noreferrer">RulesOfThumb</a></li>\n</ul>\n'}, {'answer_id': 217226, 'author': 'mmalc', 'author_id': 23233, 'author_profile': 'https://Stackoverflow.com/users/23233', 'pm_score': 3, 'selected': False, 'text': '<p>As ever, when people start trying to re-word the reference material they almost invariably get something wrong or provide an incomplete description.</p>\n\n<p>Apple provides a complete description of Cocoa\'s memory management system in <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html#//apple_ref/doc/uid/10000011" rel="noreferrer">Memory Management Programming Guide for Cocoa</a>, at the end of which there is a brief but accurate summary of the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Tasks/MemoryManagementRules.html#//apple_ref/doc/uid/20000994" rel="noreferrer">Memory Management Rules</a>.</p>\n'}, {'answer_id': 267594, 'author': 'Olie', 'author_id': 34820, 'author_profile': 'https://Stackoverflow.com/users/34820', 'pm_score': 2, 'selected': False, 'text': '<p>The answers above give clear restatements of what the documentation says; the problem most new people run into is the undocumented cases.  For example:</p>\n\n<ul>\n<li><p><strong>Autorelease</strong>: docs say it will trigger a release "at some point in the future."  WHEN?!  Basically, you can count on the object being around until you exit your code back into the system event loop.  The system MAY release the object any time after the current event cycle.  (I think Matt said that, earlier.)</p></li>\n<li><p><strong>Static strings</strong>: <code>NSString *foo = @"bar";</code> -- do you have to retain or release that?  No.  How about</p>\n\n<pre><code>-(void)getBar {\n    return @"bar";\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code>NSString *foo = [self getBar]; // still no need to retain or release\n</code></pre></li>\n<li><p><strong>The Creation Rule</strong>: If you created it, you own it, and are expected to release it.</p></li>\n</ul>\n\n<p>In general, the way new Cocoa programmers get messed up is by not understanding which routines return an object with a <code>retainCount &gt; 0</code>.</p>\n\n<p>Here is a snippet from <a href="http://www.stepwise.com/Articles/Technical/2001-03-11.01.html" rel="nofollow noreferrer">Very Simple Rules For Memory Management In Cocoa</a>:</p>\n\n<blockquote>\n  <p><em>Retention Count rules</em></p>\n  \n  <ul>\n  <li>Within a given block, the use of -copy, -alloc and -retain should equal the use of -release and -autorelease.</li>\n  <li>Objects created using convenience constructors (e.g. NSString\'s stringWithString) are considered autoreleased.</li>\n  <li>Implement a -dealloc method to release the instancevariables you own</li>\n  </ul>\n</blockquote>\n\n<p>The 1st bullet says: if you called <code>alloc</code> (or <code>new fooCopy</code>), you need to call release on that object.</p>\n\n<p>The 2nd bullet says: if you use a convenience constructor <em>and you need the object to hang around</em> (as with an image to be drawn later), you need to retain (and then later release) it.</p>\n\n<p>The 3rd should be self-explanatory.</p>\n'}, {'answer_id': 349176, 'author': 'Abizern', 'author_id': 41116, 'author_profile': 'https://Stackoverflow.com/users/41116', 'pm_score': 2, 'selected': False, 'text': '<p>There\'s a free screencast available from the iDeveloperTV Network</p>\n\n<p><a href="http://ideveloper.tv/freevideo/details?index=17012088" rel="nofollow noreferrer">Memory Management in Objective-C</a></p>\n'}, {'answer_id': 382064, 'author': 'Rob', 'author_id': 386102, 'author_profile': 'https://Stackoverflow.com/users/386102', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ll not add to the specific of retain/release other than you might want to think about dropping $50 and getting the Hillegass book, but I would strongly suggest getting into using the Instruments tools very early in the development of your application (even your first one!). To do so, Run->Start with performance tools. I\'d start with Leaks which is just one of many of the instruments available but will help to show you when you\'ve forgot to release. It\'s quit daunting how much information you\'ll be presented with. But check out this tutorial to get up and going fast:<br>\n<a href="http://www.cimgf.com/2008/04/02/cocoa-tutorial-fixing-memory-leaks-with-instruments" rel="nofollow noreferrer">COCOA TUTORIAL: FIXING MEMORY LEAKS WITH INSTRUMENTS</a></p>\n\n<p>Actually trying to <em>force</em> leaks might be a better way of, in turn, learning how to prevent them! Good luck ;)</p>\n'}, {'answer_id': 430854, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>My usual collection of Cocoa memory management articles:</p>\n\n<p><a href="http://iamleeg.blogspot.com/2008/12/cocoa-memory-management.html" rel="nofollow noreferrer">cocoa memory management</a></p>\n'}, {'answer_id': 2211835, 'author': 'Brian Moeskau', 'author_id': 108348, 'author_profile': 'https://Stackoverflow.com/users/108348', 'pm_score': 0, 'selected': False, 'text': '<p>As several people mentioned already, Apple\'s <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html" rel="nofollow noreferrer">Intro to Memory Management</a> is by far the best place to start.</p>\n\n<p>One useful link I haven\'t seen mentioned yet is <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html" rel="nofollow noreferrer">Practical Memory Management</a>. You\'ll find it in the middle of Apple\'s docs if you read through them, but it\'s worth direct linking.  It\'s a brilliant executive summary of the memory management rules with examples and common mistakes (basically what other answers here are trying to explain, but not as well).</p>\n'}]
['https://Stackoverflow.com/questions/6578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/797/']