ios - 使用 ALAssetsLibrary 多次将照片保存到图库会导致崩溃

标签 ios alassetslibrary

我有一种方法可以将照片保存到用户的照片库中。当您第一次将照片保存到库中时,此代码可以完美运行,但如果您尝试第二次保存它,应用程序将崩溃。

方法如下:

- (void)saveToLibray
{
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    // Request to save the image to camera roll
    [library writeImageToSavedPhotosAlbum:[self.image CGImage] orientation:(ALAssetOrientation)[self.image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){

        if (error) {

            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"Could not save photo to your library. Please enable Halfsies in Settings > Privacy > Photos." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertView show];

            CGImageRelease([self.image CGImage]);

        } else if (!error) {

            UIAlertView *librarySaveSuccessAlertView = [[UIAlertView alloc]initWithTitle:@"Success!" message:@"Your finished halfsie was successfully saved to your photo library!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

            [librarySaveSuccessAlertView show];

         CGImageRelease([self.image CGImage]);

        }
    }];
}

我已确保释放 CGImage 并且我也在等待 librarySaveSuccessAlertView 显示在屏幕上,单击确定按钮(cancelButtonTitle),然后我尝试再次保存。

第二次时,应用程序总是崩溃。

发生这种情况是因为库可以检测到重复的照片,还是其他原因?

编辑:崩溃详细信息

在应用程序崩溃后突出显示为绿色的行上,显示:

Thread 1: EXC_BAD_ACCESS(code=1, address=0x657471ef)

编辑 2:好的,所以我现在意识到这很可能是因为我正在尝试向已释放的对象发送消息。我很困惑我应该如何处理这件事。即使我释放了 self.imageCGImage 数据,我仍然应该能够在第二次保存时再次访问它,对吗?

最佳答案

正如您已经怀疑的那样(干得好),问题出在这一行:

CGImageRelease([self.image CGImage])

当且仅当您调用CreateCopy 方法获取CG 类型对象时,您才需要释放它。例如,您可能通过调用函数 CGImageCreate() 获得了这个 CGImage。你在这里没有做过那样的事情,所以这不是你要释放的对象。所以简单地删除这些行,停止不正确的内存管理,一切都会好起来的。

关于ios - 使用 ALAssetsLibrary 多次将照片保存到图库会导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24941571/

相关文章:

iphone - iOS - ALAssetsLibrary 使用的缓存数据未更新

iphone - 无法从 Assets URL 加载图像

iOS block 在什么线程上调用?

ios scrollViewDidEndDecelerating 不适用于 UICollectionView,但适用于 UITableView

ios - 如何编辑 backBarButtonItem (UINavigationItem) 的背景颜色? iOS 4.3 问题

ios - 在设备中安装应用程序时获取EXC_BAD_ACCESS,核心图形

ios - ALAssetLibrary 音频

ios - ALAssetsLibrary.assetForURL 中的额外参数 "result block"

ios - 在设备上拍照时应用程序崩溃 - uipickercontroller

ios - 如何将捕获的图像保存到文档目录中