2012-07-01 121 views
1

在我的iPhone應用程序的我viewDidLoad方法中,我有以下代碼:改變一個UIImageView的動畫圖像

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

後來在應用程序下面的代碼被稱爲:

[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]; 

這導致應用程序崩潰,並在線上使用EXC_BAD_ACCESS zombie[i].animationImages = flyingZombieImages;

flyingZombieImages使用以下代碼進行初始化:(zombieImages以相同方式初始化)

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

爲什麼會發生這種情況?有沒有解決方法?

+0

哪一行崩潰? –

+0

zombie [i] .animationImages = flyingZombieImages; –

+0

flyingZombieImages如何初始化?似乎是這是什麼原因造成的問題。你有沒有調試過,看看數組是否真的有效? – Dima

回答

1

正如迪馬提到flyingZombieImages可能沒有正確初始化,這是導致崩潰。然而,還有另外一個問題,以及當你創建的UIImageView的新實例:

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

此時你已經存儲在這個變量的舊的UIImageView的引用。你失去了對它的引用,很可能會泄漏它的內存。您也希望從視圖層次結構中刪除舊的UIImageView並添加新的UIImageView。

一個更好的辦法反而使用原來的UIImageView,並用替換該行改變自己的形象:

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