繁体   English   中英

iOS addSubview和removeFromSuperview导致内存泄漏

[英]iOS addSubview & removeFromSuperview causing memory leaks

我有以下问题:

我从扩展UIViewController类的类中获得一个实例,在该类中,我将UIImage添加到UIImageView,然后使用此方法“ addSubview:”将UIImageView添加到self.view中:[self.view addSubview:imageView],最后添加使用[[[UIApplication sharedApplication] keyWindow] addSubview:[self view]]到窗口中的self.view,当我单击关闭按钮时,我正在清除self.view(删除子视图“ UIImageView”)并删除self从窗口查看。

现在的问题是,当我使用同一实例向其他图像添加其他UIImageView时,即使我已释放它们并将它们从Superview中删除,也无法从内存中释放第一个数据。 以下代码说明了该问题。

- (void) setImageWithURL: (NSString *)url {

    NSData * imageData =NSData * imageData =[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];

    if (imageData) {
            UIImage *image = [[UIImage alloc]initWithData:imageData];
            [[[UIApplication sharedApplication] keyWindow] addSubview:[self view]];
            [self createViewWithImage:image];
            [image release];
}

-(void) createViewWithImage: (UIImage *) image{
    [self.view setHidden:false];
     UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
     [self.view addSubview:imageView];
     [imageView release];
}

// for removing the imageView when i click on close button
-(void) closeView{
            for (UIView *subView in self.view.subviews) {
                  [subView removeFromSuperview];
             }
            [self.view removeFromSuperview];

}

注意:我已经使用xcode工具来测试内存分配。

更新:经过更多的研究..导致内存泄漏的不是addSubview&removeFromSuperview ..其NSData。 我不知道为什么它没有从内存中释放出来。 我进行了一些更改以测试其是否真正是NSData,我将图像保存在本地并使用两种情况设置了图像:

//Case 1:
NSString *path = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
NSData * imageData =[[NSData dataWithContentsOfFile:path];
image = [[UIImage alloc]initWithData:imageData];


//Case 2:

NSString *path = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
image = [[UIImage alloc] initWithContentsOfFile:path];

我发现情况一使内存泄漏,而情况二却很干净。

现在,UIImage无法在不使用NSData的情况下获取图像,并且由于某些原因未发布NSData ..所以我该如何解决这个问题!

你有没有:

[super dealloc];

在派生类的dealloc中?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM