Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can do it both ways: either return an object that is owned by the caller, or return an object that is not owned by the caller (e.g., an autoreleased object). Regardless of which strategy you choose, follow the naming conventions. For instance,</p> <pre><code>- (NSString *)fullNameCopy { return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName]; } </code></pre> <p>returns an <code>NSString</code> object that is owned by the caller. The method name is <code>fullNameCopy</code>, which follows the naming rules: a method that contains ‘copy’ in its name returns an object that’s owned by the caller. The return value is not placed in the autorelease pool.</p> <p>Alternatively,</p> <pre><code>- (NSString *)fullName { return [NSString stringWithFormat:@"%@ %@", self.firstName, self.LastName]; } </code></pre> <p>or</p> <pre><code>- (NSString *)fullName { NSString *s = [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName]; return [s autorelease]; } </code></pre> <p>return a string that is not owned by the caller, and the method name doesn’t contain alloc, new, or copy. The return value is autoreleased, hence it will be deallocated when the corresponding autorelease pool is drained unless the caller explicitly chooses to retain it.</p> <p>That said, in your particular scenario, the second strategy — returning an object that is not owned by the caller — looks like a better solution. The caller will most likely either process the object immediately (so he won’t be interested in owning the object) or keep it in a property (which will most likely be either a copy or a retain property).</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