2011-03-29 35 views
1

我已经在此处发布此内容之前搜索了最好的内容。下面是导致内存泄漏的代码。包括autorelease修复了内存泄漏,但我更感兴趣知道我在这里做错了什么。如果我拥有它,我应该释放它,这是我想要做的:) THankyou提前的帮助。 ContainerView是一个UIView,我将其欢迎文本添加到它。正在发布UIImageView,并且仍然发生内存泄漏

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]; 
+0

“包括autorelease修复内存泄漏”,是否意味着您正在autoreleasing图像视图并调用它的发布? (BTW,搞笑图片名称) – Merky 2011-03-29 18:34:40

回答

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

后以前alloced welcomeText二号线已遗失,您正在泄漏内存。第1行后,图像视图被分配,并且welcomeText指向该视图。在第二行中,另一个图像视图被分配,现在welcomeText指向这个新的视图。因此,您没有任何指向第一个分离的图像视图的指针,并因此泄漏。

这里你并不需要第一行。

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

+1是的,我也同意。 – 2011-03-29 18:37:49

+0

谢谢:)愚蠢的错误 – Nash 2011-03-29 18:38:20

0

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