【问题标题】:UIImageView crashes due to memory warning, trying to load a huge array of imagesUIImageView 由于内存警告而崩溃,试图加载大量图像
【发布时间】:2013-07-25 13:12:27
【问题描述】:

我正在制作一个类似于电影播放器​​的应用程序,但我没有显示视频,而是将电影放在图像帧中。滑块用于前后移动“电影”,如果松开,“电影”会自动播放到一章。 我通过使用UIImageView 并在滑块的每个值更改时更改image 属性来实现此目的。一段时间后,应用程序由于内存警告而崩溃。我不能使用 UIImage 的动画,因为我想通过滑动滑块来控制位置(也就是可见的图像/帧)。 所以我有一个 ImageManager 类,它在初始化时将字符串中的所有图像名称加载到一个数组中(总共 1500 个图像,每个图像大约 150kb)。

- (id) initWithCanvas:(UIImageView*) canvasView{
    self = [super init];
    if (self) {
        totalImages = 1500;
        self.canvas = canvasView;
        self.images = [[NSMutableArray alloc] init];
        for (int i=0; i<totalImages; i++){
            [self.images addObject:[NSString stringWithFormat:@"frame_%04d.jpg", i]]; 
            i = i + 4; // I use this to skip 4 frames
        }
        previewsImageIndex = -1;
        [self setImageAtPosition:0];
    }
    return self;
}

然后我有一个在 UISlider 的值更改时触发的函数,它找到当前图像名称并从图像名称构造一个 UIImage 并将其设置为 UIImageView

- (void) setImageAtPosition:(CGFloat)percentage{
    currentImage = nil;
    int position = percentage * [self.images count];
    if (position != previewsImageIndex){
        previewsImageIndex = position;
        NSLog(@"Got image:%d at percentage: %f", position, percentage);
        if (position < [self.images count]){
            self.canvas.image = nil;
            currentImage = [UIImage imageNamed:[self.images objectAtIndex:position]];
            [self.canvas setImage:currentImage];
            currentImage = nil;
            //[currentImage release];
        }
    }
}

即使我将 currentImage 和 canvas.image 设置为 nil,应用程序仍然会在一段时间后崩溃。我不明白我在哪里有内存泄漏。另外,我用 ARC 编码,所以没有发布。

除了拥有 UIImage 视图之外,还有其他更好的方法吗?我想要逐帧查看功能,而 MPMoviePlayer 或 AVPlayer 无法进行细粒度的擦洗。

【问题讨论】:

  • 不要使用imageNamed,因为它会缓存你的图片。
  • 请出示currentImage的声明。
  • @MarcusAdams UIImage* currentImage;但做坏事的是imageNamed

标签: ios memory-management memory-leaks uiimageview uislider


【解决方案1】:

您将需要使用[UIImage imageWithContentsOfFile:@""] 方法,因为它不会缓存图像。 imageNamed: 缓存通过它加载的所有图像。

【讨论】:

  • 成功了!尽管我必须使用NSString *fileLocation = [[NSBundle mainBundle] pathForResource:[self.images objectAtIndex:position] ofType:@"jpg"]; 获得完整路径。我想我应该更频繁地阅读文档,因为它在那里描述了缓存
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 1970-01-01
  • 2012-11-28
相关资源
最近更新 更多