【问题标题】:Trying to reuse variable to avoid abandoned memory尝试重用变量以避免废弃内存
【发布时间】:2011-04-23 15:27:16
【问题描述】:

我有一个 TapDetectingImageView 类,它在使用后属于内存,因为我没有在我的代码中重用它。 我现在更改我的代码以重用它,而不是每次都重新创建一个新代码。

目标是配置 TapDetectingImageView 对象并将其放入视图中。我会做 8 次,但使用下面的代码,只显示最后一个。我确定我错过了什么,但是什么? ;)

持有imageViews的视图是potatoeView。我正在通过以下方式添加新的 TapDetectingImageView:

[potatoeView addSubview:imageView];

那段代码有什么问题?

for (int i = 0; i <= numberOfPotatoes-1; i++)
    {
        NSLog(@"potatoesView Generation : %d",i);

        NSArray *imgArray = [[NSArray alloc] initWithArray:[p objectAtIndex:i]];
        UIImage *img1 = (UIImage *) [imgArray objectAtIndex:0];
        UIImage *img2 = (UIImage *) [imgArray objectAtIndex:1];
        NSString *imgName = (NSString *) [imgArray objectAtIndex:2];

        if (imageView == nil) {
            imageView = [[TapDetectingImageView alloc] initWithImage:img1 imageHighlighted:img2];
        }else {

            [imageView setImage:(UIImage *)img1];
            [imageView setImageHighlighted:(UIImage *)img2];

        }

        [imageView setDelegate:self];

        // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"

        CGRect rect = imageView.frame;

        rect.size.height = [potatoesSize floatValue] ;
        rect.size.width = [potatoesSize floatValue] ;

        imageView.frame = rect;

        [imageView setName:(NSString *)imgName];


        imageView.tag = i+1;    // tag our images for later use when we place them in serial fashion

        NSValue *val = [potatoesSizeAndPositions objectAtIndex:i];
        CGPoint point = [val CGPointValue];
        imageView.center = point;

        [potatoeView addSubview:imageView];

        [imgArray release];
    }

【问题讨论】:

    标签: iphone cocoa-touch memory-management uiimageview


    【解决方案1】:

    您似乎从根本上误解了您的观点是如何得出的。当您使用八个不同的位置和图像设置相同的视图实例时,它不会在某个画布上“标记”它们。在主运行循环开始绘制您的视图之前,不会查询它的状态,此时它会询问您的视图的框架和内容等等来绘制它。如果你想用 UIView 绘制八个不同的图像,你需要八个不同的视图。

    【讨论】:

      【解决方案2】:

      您只能创建一个视图,将其设置为子视图,然后将其更改 n-1 次。删除 if (imageView==nil) 并创建全部 8 个。

      【讨论】:

      • 您好,这就是我之前所做的,但是当关闭视图时,8 个视图仍在内存中。我没有泄漏也没有僵尸,但在设备上测试时似乎有一些废弃的内存会产生低内存崩溃......我正在寻找如何解决这个问题......我将回到以前的代码创建 8 个视图并发布之后...感谢您的回答。
      • 如果您遇到低内存崩溃,这不是因为八个 UIView。使用各种分析工具来查找问题,而不是对您的应用程序进行猛烈的攻击。
      • ok ooook ;-) 我已经回来了,通过仪器分析,我似乎已经发布了一些东西……必须重新分析我的代码……抱歉 ;-)
      • 使用静态分析器 (Cmd-Shift-a) 构建。它擅长发现更常见的内存泄漏。
      猜你喜欢
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      相关资源
      最近更新 更多