简体   繁体   中英

Change the animation images of a UIImageView

In my viewDidLoad method of my iPhone app I have the following code:

zombie[i].animationImages = zombieImages;
        zombie[i].animationDuration = 0.8/zombieSpeed[i];
        zombie[i].animationRepeatCount = -1; 
        [zombie[i] startAnimating];

Later on in the app the following code is called:

[zombie[i] stopAnimating];
                zombie[i] = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zh.png"]];
                zombie[i].animationImages = flyingZombieImages;
                zombie[i].animationDuration = 0.8/zombieSpeed[i];
                zombie[i].animationRepeatCount = -1; 
                [zombie[i] startAnimating];

This causes the app to crash, with EXC_BAD_ACCESS on the line zombie[i].animationImages = flyingZombieImages;

flyingZombieImages is initialized with the following code: ( zombieImages is initialized the same way)

NSMutableArray *flyingZombieImages = [NSMutableArray array];
    for (NSUInteger i=1; i <= 29; i++) {
        NSString *imageName = [NSString stringWithFormat:@"flzom%d.png", i];
        [flyingZombieImages addObject:[UIImage imageNamed:imageName]];
    }

Why is this happening? Is there a workaround?

As Dima mentioned flyingZombieImages is likely not initialized properly, which is causing the crash. However, there is another problem as well when you create the new instances of UIImageView:

zombie[i] = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zh.png"]];

At this point you already have a reference to the old UIImageView stored in this variable. You are losing the reference to it and most likely will leak its memory. You also would want to remove the old UIImageView from the view hierarchy and add the new one.

A better way is instead to use the original UIImageView and change its image by replacing this line with:

zombie[i].image = [UIImage imageNamed:@"zh.png"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM