2011-11-06 73 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