badmanj
badmanj

Reputation: 198

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.

Upvotes: 4

Views: 2567

Answers (3)

Valera
Valera

Reputation: 111

You should NOT release this object! Apple says: "Return Value An autoreleased data object containing the PNG data, or nil if there was a problem generating the data." (see UIImagePNGRepresentation reference)

Upvotes: 0

olliej
olliej

Reputation: 36793

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.

Upvotes: 4

Marc Charbonneau
Marc Charbonneau

Reputation: 40513

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.

Upvotes: 4

Related Questions