我正在尝试创建一个照片查看器,就像iOS中的苹果照片应用程序一样。布局是正常的,但它收到内存警告,然后崩溃。为什么?即使我从应用程序的documents文件夹中加载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对象。
发布于 2012-03-31 03:25:10
你应该懒惰地加载你的图像,同时重用你的按钮,以考虑到大量图像的可能性。
要实施以下操作:
此外,如果7/8图像使你的应用崩溃,听起来你正在处理一些非常大的图像文件。尝试在documents目录中提供内容的缩略图大小版本(无论您的按钮的确切大小是多少),或者如果图像是动态的,请参阅this post获取操作方法。
发布于 2011-12-20 23:27:23
如果你可能正在使用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;
}https://stackoverflow.com/questions/8577523
复制相似问题