Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Notice that your code could be rewritten as:</p> <pre><code>UIImage *image = [[UIImage alloc] initWithData:myData]; UIImage *scaledImage = [image scaleToSize:size]; image = scaledImage; </code></pre> <p>so let’s see what happens:</p> <ul> <li><code>image</code> is obtained via <code>alloc</code>, hence you own that object</li> <li><code>scaledImage</code> is obtained via a method that returns an autoreleased object since <code>UIGraphicsGetImageFromCurrentImageContext()</code> returns an autoreleased object</li> <li>you own the original <code>image</code> but you don’t own <code>scaledImage</code>. You are responsible for releasing the original <code>image</code>, otherwise you have a leak.</li> </ul> <p>In your code, you use a single variable to refer to both objects: the original image and the scaled image. This doesn’t change the fact that you <em>own</em> the first image, hence you need to release it to avoid leaks. Since you lose the original image reference by using the same variable, one common idiom is to send <code>-autorelease</code> to the original object:</p> <pre><code>UIImage *image = [[[UIImage alloc] initWithData:myData] autorelease]; image = [image scaleToSize:size]; </code></pre> <p>Or, if you’d rather release the original image instead of autoreleasing it,</p> <pre><code>UIImage *image = [[UIImage alloc] initWithData:myData]; UIImage *scaledImage = [image scaleToSize:size]; [image release]; // use scaledImage from this point on, or assign image = scaledImage </code></pre> <p>IMO, it doesn’t make sense to change <code>scaleToSize:</code>. It is an instance method that creates an (autoreleased) image based on a given <code>UIImage</code> instance. It’s similar to <code>-[NSString stringByAppendingString:]</code>, which creates a (an autoreleased) string based on a given <code>NSString</code> instance. It doesn’t and shouldn’t care about the ownership of the original string, and the same applies to your <code>scaleToSize:</code> method. How would the method know whether the caller wants to keep the original image?</p> <p>I’d also rename <code>scaleToSize:</code> to <code>imageByScalingToSize</code> to make it similar to Cocoa’s naming convention — you’re getting an image by applying an operation to an existing image.</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