views:

147

answers:

2

I am getting errors of type EXC-BAD-ACCESS where I create a new UIImage instance by assigning the value of a pre-existing UIImage (as below) and I am trying to figure out what the problem is. There is a heap of code to sort through and I am not sure where to start so I won't bother posting source -- but it might help me in my investigation of any of you could tell me What exactly is going on (memory-wise) when I create a new UIImage by assigning from another?

(in the .h)

UIImage* myExistsImage;

...

@property (retain) UIImage* myExistsImage;

...

-(UIImage*)rotateImage:(UIImage*)imageToRotate;



----------------------------------------------------


(in the .m)
@synthesize myExistsImage;

...

UIImage* myNewImage = [self rotateImage:myExistsImage];


...

-(UIImage*)rotateImage:(UIImage*)imageToRotate
{

UIImage* rotatedImage = imageToRotate;

//Rotate Image Here (details omitted)...

 return rotatedImage;
}
+2  A: 
UIImage* rotatedImage = imageToRotate;

In that line, you're not creating a new UIImage object; you're simply creating a new pointer to the old one. If Rotate Image Here implies in-place modifications to rotatedImage, then you're actually modifying myExistsImage as well.

If you want to create a new UIImage object to hold the rotated object, you'll need to explicitly do so with the UIImage alloc and init methods.

BJ Homer
Oh. So since it is just a pointer, if the actual image data it points gets released then this might be the cause of my EXC-BAD-ACCESS correct? Thanks!
RexOnRoids
Yes. If you want the data to remain until both pointers are done, just add a retain when you copy the pointer.
BJ Homer
+2  A: 

With code like:

UIImage* src;
UIImage* dst = src;

... all you're doing is copying a pointer. In order to make sure that dst and src are going to keep pointing to a valid UIImage you need to call retain on the UIImage twice -- once for src and once for dst. When you no longer need a pointer, you should call release on the UIImage- when all the pointers have gone away the last call to release will deallocate the UIImage. What you're seeing is that the UIImage is being released while you're still interested in using it; you need to retain it, then, to keep that from happening.

fbrereto