Dealing with an animation of large images, you can do this: Simply alloc memory for each of the large images…
NSArray *imagesForLargeAnimation;
#define IMG(X) [[UIImage alloc] \
initWithContentsOfFile:[[NSBundle mainBundle] \
pathForResource:@X ofType:@"tif"]]
imagesForLargeAnimation = [[NSArray alloc] initWithObjects:
IMG("01"),
// (since we are allocing that image, of course we must release it eventually.)
IMG("02"),
IMG("03"),
....
IMG("42"),
nil];
animationArea.animationImages = imagesForLargeAnimation;
//blah blah...
Later, once the animation has been stopped and is no longer being shown onscreen, to clean up the memory you’d have to do this:
-(void) cleanUpTheMemoryInTheBigAnimation
{
//blah blah..
// for each of those big images in the array, release the memory:
for (UIImage *uu in imagesForLargeAnimation)
[uu release];
// release the array itself
[imagesForLargeAnimation release];
imagesForLargeAnimation = nil;
Now, this all works perfectly and efficiently, it will not leak nor overuse memory if you repeatedly use different large animations.
The only problem is, of course you get the clang warning: “Potential leak of an object allocated on line 69”, indeed you get scores of those warnings, one for each alloc.
What’s the best idiom to avoid these warnings — and make it safer and tighter?
Does anyone know?
For example, if you use autorelease, thus, in the code example above you’d use autorelease in the IMG define…
…in fact, when you release the NSArray (ie, [imagesForLargeAnimation release] ) … at that point it will autorelease all the objects in the array? Is that correct? Or??
(Or should I be using some sort of newBlah function to put the images in, or .. ??)
If anyone knows the correct approach here to avoid the “potential leak”, thanks!!!
{PS a reminder to basically never use imageNamed:, it’s hopeless: it’s only suitable for small UI-usage-type images. Never use imageNamed!}
You don’t need to keep the images retained – the NSArray will do that for you.
Try this :
and you don’t now need this code :
FYI (1) :
Were you to use imageNamed you would not get a warning because imageNamed returns already autoreleased objects but alloc/initWithcontentsOfFile does not 🙂
FYI (2) :
There is a method on NSArrays which performs a selector on all the objects :