Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What you have done will work. You can <code>retain</code> and <code>release</code> objects from any scope you choose, so long as it all evens out (and the object is deallocated when it is no longer needed by any other object).</p> <p>But what you are doing is not conventional. If you want to allow the object to live on past the life of a method (so that you can <code>return</code> it and have it picked up by the method caller) then you should use <code>autorelease</code>.</p> <p>In your example, the first method should probably not retain ownership of the string. It should release it and let the caller pick it up. But, of course, if you <code>release</code> it in the method it will be instantly deallocated. So instead you can <code>autorelease</code> it. By autoreleasing it, your first method is saying <em>"I no longer need this object and relinquish my ownership, but please keep it in memory a little while longer so my caller can retain it if it needs to"</em>.</p> <p>Here's an example:</p> <pre><code>- (NSString *)createString { /* Create a string. This method owns it. */ NSString *str = [[NSString alloc] init]; /* Autorelease it. This method does not own it, but wants it to stay in memory temporarily. */ [str autorelease] /* Return it. It will stay in memory till the end of the current run loop */ return str; } - (void)viewDidLoad{ NSString *name = [self createString]; /* We now have a copy of the string. Nobody owns it. */ /* It is due to be released at the end of the current run loop. */ /* If we want to take ownership of it and prevent deallocation, we should retain it. */ [name retain]; } </code></pre> <p>This behaviour is used all throughout the Cocoa APIs. When you see class methods that return a new object, that object will be autoreleased. For example, when you call <code>[NSArray arrayWithObjects:@"One", @"Two", @"Three", nil]</code> you are asking the NSArray class to create an array for you. If exists outside of the <code>arrayWithObjects:</code> method thanks to its autoreleased status. If you do not <code>retain</code> it, it will be released at the end of the current run loop.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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