使用ALAssetsLibrary的EXC_BAD_ACCESS错误assetForURL:resultBlock:failureBlock:

时间:2011-05-16 14:55:10

标签: objective-c cocoa-touch ios memory-management alassetslibrary

我正在尝试从用户选择的图像中读取EXIF数据。我正在使用ALAssetLibrary。到目前为止,我已设法获取assetForURL:resultBlock:failureBlock:方法所需的参考网址,但当我尝试对参考网址执行任何操作时,我收到EXC_BAD_ACCESS错误。

在使用它之前,NSLog的URL会产生(据我所知)正确的字符串:

  

assets-library://asset/asset.JPG?id=1000000003&ext=JPG

我一直试图解决这个问题,但我似乎每次都会遇到死胡同。我必须承认我是Objective-C的新手,所以请随意批评我的代码。

代码(远离完整的类,但我认为它应该足够了):

//Class_X.m

-(void)readExifDataFromSelectedImage:(NSURL *)imageRefURL    
{
    void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *) = ^(ALAsset *asset)
    {
       NSLog(@"Test:Succes");
    };

    ALAssetsLibrary *myAssetLib;
    NSLog(@"%@",imageRefURL);
    [myAssetLib assetForURL:imageRefURL
                resultBlock:ALAssetsLibraryAssetForURLResultBlock 
               failureBlock:^(NSError *error){NSLog(@"test:Fail");}];
}

//Class_Y.m
//This  also conforms to the UIImagePickerControllerDelegate And the NavigationControllerDelegate protocols:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    self.referenceURL = [info valueForKey:@"UIImagePickerControllerReferenceURL"];
    NSString *mediaType = [info
                       objectForKey:UIImagePickerControllerMediaType];
    [self dismissModalViewControllerAnimated:YES];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        imageView.image = selectedImage;
        btnNoPicture.hidden = YES;
        btnSelectPicture.hidden = YES;
        btnTakePicture.hidden = YES;
        imageView.hidden = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Use this image?" 
                                                        message:@"Are you sure you want to use this image?" 
                                                       delegate:self 
                                              cancelButtonTitle:@"No" 
                                              otherButtonTitles:@"Yes", nil];
        [alert show];
        [alert release];
    }

}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        //Do not use the selected image.
        imageView.image = nil;
        imageView.hidden = YES;
        //Restart picking process
    }
    else
    {

        // I have an instance variable of type Class_X which i use 
        // throughout this class; let's call this variable "report". 
        // I also have the referenceURL stored as an instance variable.
        [self.report readExifDataFromSelectedImage:self.referenceURL];
    }

}

1 个答案:

答案 0 :(得分:3)

EXC_BAD_ACCESS通常是过度释放对象(悬空指针)的结果。由于库是异步操作的,因此在readExifDataFromSelectedImage:方法返回后执行块,因此此时imageRefURL可能已经解除分配。在请求资产之前尝试retain URL,并在成功和失败块中尝试release