Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are two totally different answers depending on whether or not you're using ARC. Since the ARC environment is pretty straight forward, I'll just answer from a pre-ARC perspective. The main thing to understand is that all of the talk around property retain semantics is just a distraction from the main point: <strong>If you take ownership, you must relinquish it</strong>. Relinquishing ownership is done via <code>-release</code>. So, what you need to understand is "What counts as taking ownership?"</p> <p>By convention, any time you send a message to class that contains any of [<code>new</code>, <code>alloc</code>, <code>retain</code>, <code>copy</code>], you now own that object. The compiler generates setter methods for Objective C Properties depending on the ownership policies you specify. For example...</p> <pre><code>@property (..., retain) NSMutableArray *myArray; @synthesize myArray = _myArray; </code></pre> <p>This generates a method that looks like this<sup>1</sup>:</p> <pre><code>- (void)setMyArray:(NSMutableArray *)myArray { // This is oversimplified, just to illustrate the important point. // Again, this is NOT the way a setter would actually be synthesized. [_myArray release]; _myArray = [myArray retain]; } </code></pre> <p>So now, when you say something like <code>self.myArray = someArray</code>, you know you've sent a retain message to <code>someArray</code>, and you're responsible for releasing it later. The ideal way to do that is to say <code>self.myArray = nil</code>, because it releases the old value before retaining <code>nil</code>. Note that it's also perfectly safe to send that message, even if you never set anything to the <code>myArray</code> property, because sending messages to <code>nil</code> is okay. That's why it's common to <em>always</em> set owned properties to <code>nil</code> when you're done with them, regardless of how they're being used. </p> <p><hr></p> <p><sup>1</sup> For a study on how accessors should actually work, see <a href="http://cocoawithlove.com/2010/06/assign-retain-copy-pitfalls-in-obj-c.html" rel="nofollow">this article</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