iOS - Bad Access when calling ALAssetsLibrary several times

332 Views Asked by At

When a user uploads a picture from the iPhone gallery, I extract the location using ALAssetsLibrary:

ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
            [assetslibrary assetForURL:urlPhoto
                           resultBlock:^(ALAsset *asset) {
                               CLLocation *location = [asset valueForProperty:ALAssetPropertyLocation];
                           } failureBlock:^(NSError *error) {
                               NSLog(@"Can not get asset - %@",[error localizedDescription]);
                           }];

However, if the user uploads a picture and then returns to the upload screen and upload another, after three or four uploads the app crashes on EXC_BAD_ACCESS, when running the assetForURL:resultBlock:failureBlock: method.

I guess it happens since the assetForURL:resultBlock:failureBlock: runs async and the ALAssetsLibrary is released for some reason, though it cannot run simultaneously the way I've built the app.

How can I prevent it from crashing?

EDIT

Although the crash was always at this point (due to the earlier dismiss), the error occurred because of a UITableView that was deallocated earlier, but at this point referred to its delegate/datasource. the fix was adding:

- (void) dealloc
{
    myTableView.dataSource = nil;
    myTableView.delegate = nil;
}

at the end of the UIViewController that had the TableView.

1

There are 1 best solutions below

1
On

Just change your object to property .

interface:

@property (nonatomic, strong) ALAssetsLibrary* assetslibrary;

Than call implementation:

if (self.assetslibrary == nil) {    
    self.assetslibrary = [[ALAssetsLibrary alloc] init];
}
[self.assetslibrary assetForURL:urlPhoto
                           resultBlock:^(ALAsset *asset) {
                               CLLocation *location = [asset valueForProperty:ALAssetPropertyLocation];
                           } failureBlock:^(NSError *error) {
                               NSLog(@"Can not get asset - %@",[error localizedDescription]);
                           }];