Re: NSImageView setImage & when to release NSImage...
Re: NSImageView setImage & when to release NSImage...
- Subject: Re: NSImageView setImage & when to release NSImage...
- From: Ambroise Confetti <email@hidden>
- Date: Fri, 24 Oct 2003 14:21:56 +0200
Le vendredi, 24 oct 2003, ` 13:10 Europe/Paris, Brad Peterson a icrit :
If my goal is to display an image stored on disk, I might do something
like...
myImage = [[NSImage alloc] initByReferencingFile:filename];
[myImageView setImage: myImage];
Yes?
So... in this scenario, when does myImage get released? Am I
responsible for releasing it? I would think so, but I'm unclear on
whether NSImageView "needs" the NSImage once you've called setImage...
or, perhaps it's smart enough to release it when it's done?
If you do it like that and never release the image, your code will leak
memory. The best alternative would be:
myImage = [[[NSImage alloc] initByReferencingFile:filename]
autorelease];
[myImageView setImage:myImage]; // myImage is retained by myImageView
The general rule is: you are responsible for releasing objects that you
have allocated (for a certain definition of "to allocate" being a bit
more complex than simply using alloc). When you pass the image to the
image view, the image view will retain it, so you can release if
safely. Calling autorelease on your image means "release it later for
me", i.e. not before the end of the current run loop. An alternative to
the above code would be:
myImage = [[NSImage alloc] initByReferencingFile:filename];
[myImageView setImage:myImage]; // myImage is retained by myImageView
[myImage release];
The image view will release the image when it no longer needs it.
Generally, methods that don't retain their arguments are clear about
the fact in their documentation.
Can anyone clarify what is probably a very basic thing I've somehow
overlooked?
There are very simple memory management rules to follow. You will find
them in the Cocoa developer documentation, under the topic Memory
Management. Every Cocoa/Obj-C developer should read this.
Ambroise
http://www.cellulo.info/
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.