2012-02-20 24 views
0

我是一个Java程序员的新目标C,所以请温柔:)呼吁保留,retainCount分析EXC_BAD_ACCESS与释放

上调用的对象上释放I'getting的errorr消息说EXC_BAD_ACCESS: 我读文件及本网站的线程,但我看到交代不清我的数据

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

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

记录的保留数为:1

在代码导致该dealloc的我:

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]; 

在decodeImage以下是怎么回事:

- (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]; 
} 

有几件事情puzzeling我:

  1. 从什么理解retainCount增加调用保留或通过实例化一个新的对象,而不是像在自我setImage中那样通过将一个var分配给另一个var:i];然而我看到retaincount增加了一个
  2. 在调用[d版本]之前记录retainCount是2,在方法dealloc中计数是1
  3. 如果计数为1,为什么我会得到EXC_BAD_ACCESS? ?

编辑:加入附加的代码的请求

@implementation Decoder 

@synthesize image; 

图像的设置在所述第三代码是上面提到sniplet。

+0

向我们展示类Decoder的声明(尤其是定义图像的部分)。 – 2012-02-20 14:57:27

+0

需要看到的解码器类 – 0xSina 2012-02-20 15:00:47

+0

retainCount是完全无用的;别叫它。 – bbum 2012-02-20 22:01:43

回答

3

保留计数也可以通过系统(对于内置类型)以及通过retaincopy属性定义的属性来递增。您只需要你的事业的人(而不是系统保留)负责,但在尝试确定为什么你得到EXC_BAD_ACCESS时不依赖于保留计数。 XCode有一些很好的内置分析工具,可以更好地追踪访问错误。

一个重要的一点要注意:你的retaincount决不会低于1,即使释放时数为1

请参阅有关retaincount良好的信息this问题。