繁体   English   中英

imageWithContentsOfFile导致EXC_BAD_ACCESS

[英]imageWithContentsOfFile causes EXC_BAD_ACCESS

以下两个语句均有效。 但是第二条语句给了我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因为我的一些文件在Documents文件夹中,而另一些在主捆绑包中。

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

非常感谢。

您无需在代码中放置[image autorelease]。 在Cocoa框架中,仅当您键入“ alloc”或“ retain”时,才调用release或autorelease,否则将对象保留下来。 您正在使用的两个UIImage方法都没有调用alloc或keep,因此您不需要自己(自动)释放它们。

返回新对象的Convinience类方法始终自动释放,然后在以后释放,如果要防止它们释放,请调用keep。 之后,您必须调用“释放”或“自动释放”来释放对象。

如果不释放对象,它将留在内存中,占用空间。 对于iOS,我建议您避免使用自动释放,因为目标c没有交换空间并且内存有限。

第二条语句之所以起作用,是因为您很幸运(并且由于image以外的其他原因,此时image上还有一个额外的保留)。

两个函数imageNamed:imageWithContentsOfFile:暗示它们拥有返回的image对象的所有权。 这意味着您不必对此进行发布。

您拥有自己创建的任何对象。
使用名称以“ alloc ”,“ new ”,“ copy ”或“ mutableCopy ”开头的方法(例如alloc,newObject或mutableCopy)创建对象。

遵循此规则, imageWithContentsOfFile:imageNamed:都不授予您所创建对象的所有权。 您不拥有它,也不(自动)释放它。

要了解更多信息,请访问Apple内存管理指南


我很惊讶CLANG没有捕获到此错误。 在项目设置中确认“运行静态分析器”已打开。 尝试理解可可内存管理概念时,它将对您有很大帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM