2011-12-29 191 views
0

下面的两条语句都有效。但第二条语句给了我EXC_BAD_ACCESS。imageWithContentsOfFile会导致EXC_BAD_ACCESS

UIImageWriteToSavedPhotosAlbum([UIImage imageNamed:photoFilenameNoPath], self, @selector(image:didFinishSavingWithError:contextInfo:), nil); 

    UIImageWriteToSavedPhotosAlbum([UIImage imageWithContentsOfFile:filenameWithPath], self, @selector(image:didFinishSavingWithError:contextInfo:), nil); 

我跟踪它归结为[image autorelease]在:

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { 

     NSString *alertTitle; 
     NSString *alertMessage; 

     if (error == nil) { 
      // Display UIAlertView to tell user that photo have been saved 
      alertTitle = @"Photo Saved"; 
      alertMessage = @""; 
     } 
     else { 
      // Display UIAlertView with error string to tell user that photo have NOT been saved 
      alertTitle = @"Photo Not Saved"; 
      alertMessage = [NSString stringWithFormat:@"ERROR SAVING:%@",[error localizedDescription]]; 
     } 

     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertTitle message:alertMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];                            
     [alert show]; 
     [alert release];   

     [image autorelease]; 
    } 

我需要使用imageWithContentsOfFile,因为我的一些文件在文档文件夹中,还有一些是在主束。

如果我使用imageWithContentsOfFile而不是imageNamed,任何人都可以帮助解释为什么我不需要发布image

非常感谢。

回答

0

您不需要在代码中放置[image autorelease]。在Cocoa框架中,当你输入'alloc'或'retain'时,你只能调用release或者autorelease,否则留下这个对象。您使用的UIImage方法都没有调用alloc或保留,因此您不需要(自动)释放它们。

返回新对象的可信度类方法始终是自动释放的,稍后发布时,如果要防止它们被释放,请调用retain。之后,您必须调用'release'或'autorelease'来释放对象。

如果你不释放对象,它将留在占用空间的内存中。对于iOS,我建议尽可能避免使用autorelease,因为objective c没有交换空间和有限的内存。

0

第二条陈述仅适用于您是幸运的(并且因为此处还有一个额外的保留,因此您的代码以外的其他内容会导致image)。

没有一个函数imageNamed:imageWithContentsOfFile:暗示他们的名字,表示您拥有返回的image对象的所有权。这意味着你不必对它进行发布。

您拥有您创建的任何对象。
您创建使用名称以“ALLOC”对象的方法,“”,“复制”,或“mutableCopy”(例如,分配,NEWOBJECT,或mutableCopy)。

按照这一原则,既不imageWithContentsOfFile:也不imageNamed:给你所创建的对象的所有权。你不拥有它,你不(自动)释放它。请致电Apple Memory Management Guide


我很惊讶CLANG没有发现这个错误。在您的项目设置中验证运行静态分析仪已打开。在试图理解Cocoa内存管理概念时,它会帮助你很多。

相关问题