views:

617

answers:

3

Hi,

Can someone please explain why the following code causes my app to bomb?

NSData *myImage = UIImagePNGRepresentation(imageView.image);
  :
[myImage release];

If I comment out the 'release' line, the app runs... but a few times calling the function containing this code and I get a crash - I guess caused by a memory leak.

Even if I comment EVERYTHING else in the function out and just leave those two lines, when the release executes, the app crashes.

I'm sure this must be a newbie "you don't know how to clean up your mess properly" kind of thing ;-)

Cheers,

Jamie.

+4  A: 

Look into memory management, you should be able to find a few threads on it here, or you can take a look at this page. I won't go into all the rules here, but the basic issue is that myImage is autoreleased, not retained-- when you manually call release it's not paired with a retain, so when the autorelease tries to remove the (now invalid) object at the end of the run loop your application will crash. Removing the release will fix the issue, but do spend some time on getting to know the retain/release rules, it's one of the most important things to understand.

Marc Charbonneau
Thanks - I'll read up on the subject some more - the problem is my basic understanding of this, I think!
badmanj
+3  A: 

Are you sure you should be calling release -- the general rule of MacOS APIs is that methods that transfer ownership have Copy or Create in their name. I suspect you're being given a reference to the underlying image representation, rather than a copy, in which case you're releasing an object owned by something else.

olliej
Yes - you're right... I just worked through the code again, commenting code out and running step by step... I shouldn't be releasing it! Thanks - this has helped me solve this problem. Time for me to read the books some more I think :-(
badmanj
For methods, the words are `alloc`, `new`, and `copy` (and `retain`, of course). You're thinking of Core Foundation functions. Same overall idea, though. Anyway, here's the obligatory link to the memory-management rules: http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/MemoryManagement.html
Peter Hosey
A: 

I tried this. Saved me some memory management problems with NSData.

Roy