Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Releasing NSData causes exception

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.

like image 313
badmanj Avatar asked Mar 01 '23 20:03

badmanj


2 Answers

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.

like image 83
olliej Avatar answered Mar 03 '23 09:03

olliej


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.

like image 35
Marc Charbonneau Avatar answered Mar 03 '23 09:03

Marc Charbonneau