0

I'm a java programmer new to Objective C, so please be gentle :)

I'getting an errorr message saying EXC_BAD_ACCESS on calling release on an object: I read documentation and threads on this site, but I see data that's confusing me

- (void) dealloc {
    NSLog(@"dealloc in image Retain count: %i", [image retainCount]);

  [image release];//method throwing EXC_BAD_ACCESS
  ..............
}

the logged retain count is: 1

In the code that is causing the dealloc I have:

UIImage *scrn = [[UIImage alloc] initWithCGImage:newImage];
NSLog(@"in after instantiation Retain count: %i", [scrn retainCount]);// logs retain count of 1
CGImageRelease(newImage);
Decoder *d = [[Decoder alloc] init];
.....
NSLog(@"in before decoding Retain count: %i", [scrn retainCount]);// logs retain count of 1
decoding = [d decodeImage:scrn cropRect:cropRect] == YES ? NO : YES;
NSLog(@"in after decoding Retain count: %i", [scrn retainCount]); // logs retain count of 2
[d release]; // this line causes invocation of dealloc on the previous code sniplet
[scrn release];

In decodeImage the following is going on:

- (BOOL) decodeImage:(UIImage *)i cropRect:(CGRect)cr {
NSLog(@"Decoder.mm.decodeImage initial Retain count i : %i retaincount image %i", [i retainCount], [image retainCount]); //logs: Decoder.mm.decodeImage initial Retain count i : 1 retaincount image 0
[self setImage: i];
NSLog(@"Decoder.mm.decodeImage after setting image Retain count i : %i retaincount image %i", [i retainCount], [image retainCount]);//logs: Decoder.mm.decodeImage after setting image Retain count i : 2 retaincount image 2

.......
return [self decode];
}

There are several things puzzeling me:

  1. From what understood the retainCount is increased by calling retain or by instantiating a new object, not by assigningment of one var to another as is done in self setImage: i]; however i see that the retaincount is increased by one
  2. Before calling [d release] the logged retainCount is 2, in the method dealloc the count is 1
  3. If the count is 1, why do I get the EXC_BAD_ACCESS ???

Edit: added additional code as requested

@implementation Decoder

@synthesize image;

The setting of image is mentioned in the third code sniplet above.

1 Answers1

3

Retain count can also be incremented by the system (for build-in types) and by properties that are defined with the retain or copy attributes. You're only responsible for the ones you cause (not the system retains), but don't depend on the retain count when trying to determine why you're getting EXC_BAD_ACCESS. XCode has some good build-in analysis tools that are better for tracking down access errors.

One important thing to note: your retaincount will never go below 1 even if you release when the count is 1.

See this question for good information on retaincount.

Community
  • 1
  • 1
N_A
  • 19,799
  • 4
  • 52
  • 98