views:

420

answers:

3

Hi,

Using Instruments, I keep on getting pointed to a memory leak with a UIImage.
I think I'm assigning and releasing the memory correctly. The leaked object in instruments is described as NSConcreteData

Is the following the correct way to assign and release a UIImage?

UIImage* flagimg = [UIImage imageWithData: [NSData dataWithContentsOfURL:url2]];    
[flagimg release];
flagimg =nil;
A: 

both imageWithData and dataWithContentsOfURL return autoreleased objects, so you should have no memory leaks in that code snippet.

Since flagimg is returned autoreleased, your [flagimg release]; call is not needed; you're over-releasing that object.

kubi
+2  A: 

[UIImage imageWithData:] returns an autoreleased object, which should not be released by you again. So this code snipped contains not a memory leak but the opposite, a double free (in the worst case).

Note that Instruments sometimes generates false positives and/or reports memory leaks in the Foundation itself (yep, they make mistakes too :-).

The fastest way to alloc/release an object is to avoid convenience initializers (like imageWithData:) and instead to something like

NSData* data = [[NSData alloc] initWithContentsOfURL:url]];
UIImage* img = [[UIImage alloc] initWithData:data];
[data release];
// use your image
[img release];

This will allocate and release your object right away and not wait until the autorelease pool is cleaned.

But please note too, that a memory leak is generally not memory that is not yet freed, but that is lost and cannot be freed anymore, so an object which will be deallocated by the autorelease pool is not considered a memory leak.

frenetisch applaudierend
Whats the consequence of a "double release" ?
dubbeat
Usually a EXC_BAD_ACCESS (commonly called segfault) which causes your program to crash. Those happen too if you have a reference to an object which is already deallocated and you try to access it.
frenetisch applaudierend
A: 

as a general rule you can say

if you create an object an theres a "init","copy" or "retain" in it, you have to release it. if not, you get an autoreleased object.

thats not always true, but in most cases

choise