Search code examples
iphoneanimationcrashblock

Crash after animateWithDuration because of bad access


Please see the below code. It shows animation effect with image.

UIImageView *imgView = [[UIImageView alloc] initWithImage:img];  // ref count = 1
int offX = imgView.frame.size.width / 6;
int offY = (imgView.frame.size.height - 44) / 6;
imgView.frame = CGRectMake(offX, offY, imgView.frame.size.width - offX * 2, 
                           (imgView.frame.size.height - 44) - offY * 2);
[overlayView addSubview:imgView];  // ref count = 2
[imgView release];  // ref count = 1
[UIView animateWithDuration:1.0 animations:^{
    [imgView setCenter:CGPointMake(TRASH_X, TRASH_Y)];
    [imgView setTransform:CGAffineTransformMakeScale(0.1, 0.1)];
    [imgView setAlpha:0.5];
} completion:^(BOOL finished) {
    [imgView removeFromSuperview]; // ref count = 0? destroy imgView object?
}];

From the above code, if I remove [imgView release] there is no crash. but, the above code makes crash from the completion routine. Why? As I think reference count changed as like the comment. Then there should be no crash.

Could you please explain why the completion routine makes crash?


Solution

  • OK. I solved my problem. In fact, problem was not in the code I showed. There was no problem in this code.

    The reason of crash is related with 'img' object which is used as initial argument of UIImageView. Actually, I accidentally released it one more time from the other place.

    I think when UIImageView object deallocated it try to release it's Image object. But, it's already deallocate so, crash happend. It just looks like [imgView removeFromSuperview] makes crash.

    Sorry for fuss.