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

Nas*_*ash 1 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];
Run Code Online (Sandbox Code Playgroud)

tas*_*oor 5

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

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

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

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