0
votes

I am adding an animated UIImageView (an explosion) to a view but it seems to not be retained. Here is the implementation of the Explosion class, a subclass of UIImageView:

@implementation Explosion

#define EXPLOSION_DIMENSION 20

- (instancetype)initAtPoint:(CGPoint)point {
   if (self = [super initWithFrame:CGRectMake(0, 0, EXPLOSION_DIMENSION, EXPLOSION_DIMENSION)]) {
      self.center = point;
      self.image = [UIImage imageNamed:@"explosion.png"];
   }
   return self;
}

- (void)boom {
   self.alpha = 0;
   [UIView animateWithDuration:0.5
                         delay:1.0
                       options: UIViewAnimationOptionCurveLinear
                    animations:^{
                                   self.alpha = 1;
                    }completion:^(BOOL finished){
                       NSLog(@"here");
                       // [self removeFromSuperview];
                    }];
}

@end

When hitting a breakpoint on NSLog(@"here"), the debugger shows no self. Huh? Any reference to self in the completion code causes a crash so I can't do a [self removeFromSuperview] there.

Here is the code in the view where it is instantiated:

   Explosion * explosion = [[Explosion alloc] initAtPoint:p];
   [_explosionImageViews addObject:explosion];
   [self addSubview:explosion];
   [explosion boom];
   NSLog(@"subviews: %d  array: %d", self.subviews.count, _explosionImageViews.count);

The view contains 8 other subviews. The output looks like this:

subviews: 9  array: 1
subviews: 10  array: 2
subviews: 9  array: 3

Note that the number of subviews resets to 9. Nowhere do I remove the explosion from its superview, it just seems to magically go away (garbage collection?). Sometimes the subviews.count gets up to 23 before it magically resets to 9.

I put in the _explosionImageViews array just to retain the objects so they would not go out of scope even though it seems that being added to the subviews of the view should already be doing this.

The animation is supposed to stay around for 0.5 seconds but stays much longer. Then several of them all disappear at the same time. Again, garbage collection?

Any ideas what is going on?

1
"Any reference to self in the completion code causes a crash" Well, you need to think about why that is. What is the crash? Are you getting a dangling pointer? If so, the problem is that some code you are not showing us is removing this view from the interface and causing it to be released. You need to track that down. Turning on NSZombies will help you.matt

1 Answers

0
votes

You're right--your explosion object is not being retained.

To you retain it, use a strong property:

@property (strong, nonatomic) Explosion *explosion;

Then, instantiate it in your implementation, like so:

self.explosion = [[Explosion alloc] initAtPoint:p];

Of course, if your explosionImageViews are being retained, then follow that property, to see if it is being released somewhere.

I hope that helps!