【问题标题】:UIImageViews added to UIScollView never get deallocated, Memory Leak?添加到 UIScollView 的 UIImageViews 永远不会被释放,内存泄漏?
【发布时间】:2011-09-28 13:38:23
【问题描述】:

这是我的第一篇文章,你是我最后的希望。

我的 iPad 应用程序中有一个包含图像的列表,如果您选择一个,我的类 MyViewController 扩展 UIViewController 被加载并显示(只需设置 window.rootViewController,使用 UINavigationController,@987654326 @ - 尝试了一切,没有任何区别)。它内部有一个UIScrollView,它使用以下代码将图像的大版本添加到UIScrollView

UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[[delegate getImageNames] objectAtIndex:(gameNr*2)]]];
tempImageView.frame = CGRectMake(0,0,tempImageView.frame.size.width/2,tempImageView.frame.size.height/2);
[self setMyImage:tempImageView];
[tempImageView release];

myScrollView.contentSize = CGSizeMake(myImage.frame.size.width, myImage.frame.size.height);
myScrollView.maximumZoomScale = 2.0;
myScrollView.minimumZoomScale = 1.0;
myScrollView.clipsToBounds = YES;
myScrollView.bounces = NO;
myScrollView.delegate = self;
[myScrollView addSubview: myImage];

myImage 是我的MyViewControllerUIImageView 类型的(nonatomic, retain) 属性。

按下按钮并返回图像列表后,我释放对MyViewController的引用,它的dealloc方法调用如下:

- (void)dealloc
{
    CFShow(@"dealloc!");
    for(UIImageView *subview in [myScrollView subviews]) {
        if(subview.frame.size.width > 20){
            [subview removeFromSuperview];
            [subview setImage:nil];
        }
    }

    [myImage setImage:nil];

    self.myScrollView = nil;
    self.myImage = nil;

    [myScrollView release];
    [myImage release];
    [super dealloc];
}

到目前为止它可以工作,但问题是,图像的内存并没有真正以这种方式释放。打开和关闭大约 12 张图像后,应用程序崩溃并出现内存警告。 我从这里得到的 report_memory 方法也证实了这一点: iOS Low Memory Crash, but very low memory usage

调用了 dealloc 方法,进行了三次检查。 我在调试器中通过断点检查了变量myImagemyScrollView,它们被dealloc 方法中的这些命令设置为0x0。为什么内存没有释放??????

感谢您的任何建议,我已经为此工作了整整三天,这让我发疯了。

【问题讨论】:

    标签: iphone ios uiscrollview uiimageview dealloc


    【解决方案1】:

    替换这个:

    self.myScrollView = nil;
    self.myImage = nil;
    
    [myScrollView release];
    [myImage release];
    

    用这个:

    [myScrollView release];
    
    self.myScrollView = nil;
    self.myImage = nil;
    

    并在您定义属性myScrollViewinit 的位置发布代码。

    而且你不需要循环for(UIImageView *subview in [myScrollView subviews])。当你 release myScrollView 对象时,它会自动释放它的所有子视图。

    【讨论】:

    • 感谢您的快速回复。像您写的那样更改代码会导致崩溃:-[UIImageView release]: message sent to deallocated instance 0x1c1320 Here the code you ask for in .h: IBOutlet UIScrollView *myScrollView; ... } @property(非原子,保留)IBOutlet UIScrollView *myScrollView; ...如您所见,我自己并没有调用 alloc,因为它是加载在一个 nib 文件中的。这可能是问题吗?问候迈克尔
    • 如果我不将图像添加到滚动视图中,我没有内存问题,是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2022-01-13
    • 2011-01-27
    相关资源
    最近更新 更多