2011-11-06 36 views
1

我在OBJ-C新手,所以我不能瞭解一些這方面的邏輯。我想了解我的代碼和應用程​​序邏輯。我的應用程序是用的UIImageView的動畫簡單的例子的修改:這是.H(在非標準基於視圖的模板)按鈕獲得EXC_BAD_ACCESS通過法的ivars

#import <UIKit/UIKit.h> 
@interface ImageAnimatorViewController : UIViewController { 
    UIImageView *animImage; 
} 
@property (nonatomic, retain) IBOutlet UIImageView *animImage; 
- (IBAction)startAnimation; 
- (NSArray*)creatAnimation:(NSString*)fileName; 
@end 

這是.M(不包括非標準的dealloc和viewDidUnload)

@synthesize animImage; 
- (IBAction)startAnimation{ 
    [animImage startAnimating]; 
}  
- (void)viewDidLoad{ 
    [super viewDidLoad]; 

    animImage.animationImages = [self creatAnimation:@"Images.jpg"]; 
    animImage.animationDuration = 1.0f; 
    animImage.animationRepeatCount = 0; 
}  
- (NSArray*)creatAnimation:(NSString*)fileName{ 
    UIImage *image = [UIImage imageNamed:fileName]; 
    NSMutableArray *animationImages = [NSMutableArray array]; 
    for (int i = 0; i<8; i++) { 
     CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, 
     CGRectMake(i*600.0f, 0.0f, 600.0f, 262.0f)); 
     UIImage *animationImage = [UIImage imageWithCGImage:imageRef]; 
    [animationImages addObject:animationImage]; 
    [animationImage release]; 
    } 
    return animationImages; 
} 

而且我」 ve xib與imageview和按鈕,但是當我按下b有控制檯中的崩潰和EXC_BAD_ACCESS。在IBAction中,我明白imageView沒有動畫圖像,但爲什麼?並有奇怪的引用計數= 3,因爲在viewDidLoad有2(以及爲什麼2?)。我在viewDidLoad中添加self和self>前綴,但它不是結果。 animationImages是(複製)屬性,所以在autorelease池被animationImages耗盡後,圖像會被保存。我非常驚訝app.10x的這種行爲!

回答

0

不釋放動畫圖像createAnimation方法。你也應該清除內存CGImageRef使用CGImageRelease

+0

非常感謝你,這是工作。但你能解釋你的答案嗎?對我來說我有內存泄漏,因爲animationImage比它需要更多的引用計數。什麼是隱藏的?) – stworks

+0

總之。如果使用** alloc **,** new **,** retain **,** copy **創建它,則應該釋放對象。你沒有使用它們來創建animationImage,所以沒有理由釋放animationImage。我可以建議你閱讀基本的內存管理規則。 PS。如果我的回答對您有用,請點擊左側的綠色勾號接受它。 – beryllium