在我的应用中,我正在加载一系列图像到我的UIImageView
,该图像已在init
方法上创建
- (UIImage *)getImage:(int)currentIndex {
NSString *path = [self getImagePath:currentIndex];
[self.imageView setAccessibilityLabel:path];
path=[bundle pathForResource:path ofType:extension];
return [UIImage imageWithContentsOfFile:path] ;
}
- (void)changeImage:(int)currentIndex {
[self.imageView setImage:nil ];
[self.imageView setImage:[self getImage:currentIndex]];
}
但是这段代码会导致内存泄漏。像
这样的东西-malloc - 7KB - imageIO - png_malloc
我尝试过“[[UIImage alloc] initWithContentsOfFile]”,但是仍然没有运气。
我在这里缺少什么。
大致全班
- (id)initWithFrame:(CGRect)frame andBundle:(NSBundle *) bundleTobeInjected {
self = [super initWithFrame:frame];
if (self) {
// Initialization code.
self.opaque = YES;
bundle=bundleTobeInjected;
commonFunctions=[[Common alloc] init];
self.imageView = [[UIImageView alloc] initWithFrame:frame] ;
[self.imageView setImage:nil ];
self.imageView.contentMode = self.contentMode;
[self addSubview:imageView];
[self setAccessibilityEnabled];
}
return self;
}
-(void)setAccessibilityEnabled
{
self.imageView.isAccessibilityElement=true;
}
#pragma mark - Custom Logic
- (NSString *)getImagePath:(int)currentIndex {
NSString *path = [NSString stringWithFormat:@"%@%d%@", prefix,currentIndex,[commonFunctions imageNamedSmartForRotationSuffix]];
NSLog(@"%@", path);
return path;
}
- (UIImage *)getImage:(int)currentIndex {
NSString *path = [self getImagePath:currentIndex];
[self.imageView setAccessibilityLabel:path];
path=[bundle pathForResource:path ofType:extension];
return [UIImage imageWithContentsOfFile:path] ;
}
-(void)changeImage:(int)currentIndex {
[self.imageView setImage:nil ];
[self.imageView setImage:[self getImage:currentIndex]];
}
-(void)dealloc{
[extension release];
[prefix release];
[defaultImage release];
[image release];
[imageView release];
[commonFunctions release];
[super dealloc];
}
答案 0 :(得分:1)
该代码不泄漏。你的泄漏是在其他地方:)
泄漏是init
方法。看看这一行:
self.imageView = [[UIImageView alloc] initWithFrame:frame];
该行创建了您拥有的图像视图,因为您使用了init
方法。然后,您将其分配给您的属性再次拥有它,因为我猜您的属性是retain
。您需要在将imageView分配给您的属性后释放它,如下所示:
self.imageView = [[[UIImageView alloc] initWithFrame:frame] autorelease];
PS你不需要这一行
[self.imageView setImage:nil ];