2011-03-29 34 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對象。在第二行中,第一行中分配的對象泄漏。