iOS - 像照片应用程序一样创建照片查看器

时间:2011-12-20 15:10:38

标签: ios memory photo automatic-ref-counting

我正在尝试创建照片查看器,例如iOS中的Apple照片应用。 布局没问题,但它收到内存警告然后崩溃。为什么?即使我从应用程序文档文件夹加载7/8图像,也会发生这种情况。我是否需要使用特定系统管理内存?我在iOS 5中使用ARC。

编辑:

代码:

for (int i=0; i<[dataSource count]; i++) {
        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[dataSource objectAtIndex:i] forState:UIControlStateNormal];
        [[button titleLabel] setText:[NSString stringWithFormat:@"%i",i+1]];
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [[button layer] setBorderWidth:1];
        [[button layer] setBorderColor:[UIColor darkGrayColor].CGColor];
        if (i==0) {
            [button setFrame:CGRectMake(x, y, width, height)];
        } else {
            if (i%5==0) {
                nRow++;
                x=18;
                [button setFrame:CGRectMake(x, (y*nRow), width, height)];
            } else {
                [button setFrame:CGRectMake(x+space+width, (y*nRow), width, height)];
                x=button.frame.origin.x;
            }
        }
        [[self view] addSubview:button];
    }

此代码的主要部分是前6行,后面是x和y。 dataSource是一个声明为属性的NSArray(非原子,强)。它包含UIImage对象。

2 个答案:

答案 0 :(得分:1)

您应该懒得加载图片,同时重复使用按钮来解释大量图片的可能性。

实施:

  1. 保留数据数组中图像文件的路径,而不是UIImage对象。使用imageWithContentsOfFile从路径获取图像:何时需要它。
  2. 将第一个z按钮加载到滚动视图中,其中z是一次显示在屏幕上的数字加上一行的值。
  3. 将我们当前所在的UIViewController设置为scrollview的委托,并通过重新定位按钮并设置适当的图像和目标来响应偏移的变化。
  4. 此外,如果7/8图像崩溃了你的应用程序,听起来你正在处理一些非常大的图像文件。尝试在文档目录中提供缩略图大小的内容版本(无论您的按钮大小是否合适),或者如果图像是动态的,请参阅this post了解操作方法。

答案 1 :(得分:0)

如果你可能正在使用ImageNamed,这篇文章对我有很多帮助:

http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/

主要

  

请勿对任何大量图像使用[UIImage imageNamed]。这是邪恶的。它会降低你的应用程序和/或Springboard,即使你的应用程序正在使用它自己只使用几乎半字节的内存。

  

最好实现自己的缓存

这是建议的缓存图像示例:

- (UIImage*)thumbnailImage:(NSString*)fileName
{
   UIImage *thumbnail = [thumbnailCache objectForKey:fileName];

   if (nil == thumbnail)
   {
      NSString *thumbnailFile = [NSString stringWithFormat:@"%@/thumbnails/%@.jpg", [[NSBundle mainBundle] resourcePath], fileName];
      thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
      [thumbnailCache setObject:thumbnail forKey:fileName];
   }
   return thumbnail;
}
相关问题