释放UIImageView并仍然导致内存泄漏

时间:2011-03-29 18:28:37

标签: iphone memory-leaks uiimageview

我在搜索之前已经搜索过我的最佳内容。下面是导致内存泄漏的代码。包括autorelease修复了内存泄漏,但我更感兴趣的是知道我在这里做错了什么。如果我拥有它,我应该释放它,这是我想要做的:) 谢谢你提前帮忙。 ContainerView是一个UIView,我正在添加我的欢迎文本。

UIImageView *welcomeText = [[UIImageView alloc] init];
welcomeText = [[UIImageView alloc] initWithFrame:CGRectZero];
welcomeText.frame = (CGRect) {  CGRectGetMidX(containerView.frame) -295 , 100.0, 590,134 };
welcomeText.autoresizingMask =  UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | 
        UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
welcomeText.image = [UIImage imageNamed:@"welcome-to-the-jungle.png"];
[containerView addSubview:welcomeText];
[welcomeText release];

2 个答案:

答案 0 :(得分:5)

UIImageView *welcomeText = [[UIImageView alloc] init];
welcomeText = [[UIImageView alloc] initWithFrame:CGRectZero];

之前分配的第二行welcomeText丢失了,你正在泄漏那个内存。在第一行之后,分配了一个图像视图,welcomeText指向它。在第二行中,分配了另一个图像视图,现在welcomeText指向这个新图像视图。因此,您没有任何指向第一个分配的图像视图的指针,因此泄漏的结果。

这里你实际上不需要第一行。

UIImageView *welcomeText = [[UIImageView alloc] initWithFrame:CGRectZero];

答案 1 :(得分:0)

您不能在第一行分配UIImageView对象。在第二行中,第一行中分配的对象泄漏。